Javascript I

Background

  • Javascript is not related to Java in anyway other than trying to get some free publicity
  • Javascript was originally intended to be a language used to interact with websites
    • First introduced in 1995 as part of Netscape Navigator

Background (cont'd)

  • Now Javascript is a standarized language that is overseen by Ecma
    • The official term for the language is ECMAScript
    • The 6th version of the standard was finalized in June, 2015
    • The 500+ page standard is available for browsing
  • Javascript has moved beyond the web for use in databases and desktop programs.

Developing Javascript Code

  • NodeJS
  • Web Browser
    • Web Console (Firefox)
    • Javascript Console (Chrome)
    • Show Error Console (Safari, after enabling developer menu)
    • Console Tool (IE 11+, Edge)

Data Types

  • Javascript is a dynamically typed language
  • Javascript provides 7 data types
    • Undefined
    • Null
    • Boolean
    • String
    • Symbol
    • Number
    • Object

Number

  • Only one type for both integers and floats
  • Also can hold one of 3 special values
    • -Infinity
    • Infinity
    • NaN

Arithmetic Examples

In [30]:
4 + 1
Out[30]:
5
In [31]:
4 - 1
Out[31]:
3
In [32]:
4 * 1
Out[32]:
4
In [33]:
4 / -2
Out[33]:
-2
In [ ]:
In [34]:
4 % -2
Out[34]:
0
In [39]:
4/0
Out[39]:
Infinity
In [40]:
Infinity / Infinity
Out[40]:
NaN
In [ ]:
In [38]:
Math.sqrt(-1)
Out[38]:
NaN
In [37]:
0/0
Out[37]:
NaN

String

  • Strings in Javascript can be delimited by either single or dobule quotes
  • A specific character at position i in a string can be access through bracket notation [i]
  • The concatenation operator is +

String Examples

In [43]:
"abc"[0]
Out[43]:
'a'
In [44]:
"abc".length
Out[44]:
3
In [45]:
"abc" + "abc"
Out[45]:
'abcabc'
In [46]:
'Someone said "this" '
Out[46]:
'Someone said "this" '

Boolean

  • The boolean values in Javascript are true and false
    • 0, NaN and "" are coerced to false
  • The operators are
    • && (and)
    • || (or)
    • ! (not)
  • To test equality there are two operators
    • == Tests the value only
    • === Tests the value and the type

Boolean Examples

In [47]:
(1 > 0 ) && (1 < 10)
Out[47]:
true
In [48]:
'1' == 1
Out[48]:
true
In [49]:
'1' === 1
Out[49]:
false
In [50]:
'1' != 1
Out[50]:
false
In [51]:
'1' !== 1
Out[51]:
true

Undefined & Null

  • A variable in Javascript that is uninitialized has a value of undefined
  • null is used in similar situations
  • Testing a variable equal to (==) null actually test null or undefined

Unefined Examples

In [52]:
var undeclared
console.log(undeclared === undefined)
console.log(undeclared === null)
console.log(undeclared == null)
console.log(null == false)
"abc"[200]
true
false
true
false
Out[52]:
undefined

Arrays

  • Arrays in Javascript are a special type of object
  • They can be initialized by listing the elements between square brackets
  • They are indexed using []
  • There are many methods of the Array object

Array Examples

In [57]:
var arr = [1,2,3,4,5,6]
console.log(arr.length)
arr.push('7')
arr
//arr.pop()
arr
6
Out[57]:
[ 1, 2, 3, 4, 5, 6, '7' ]

Type Coercion

  • When dealing with two different data types, Javascript will prefer to attempt to cast one of the types rather than throw an error
    • This is known as type coercion
  • If type coercion fails, rather throw an error, NaN or undefined are usually returned

Type Coercion Examples

In [58]:
2 - '20'
Out[58]:
-18
In [65]:
5 + Number|('1')
Out[65]:
1
In [66]:
5 + '1'
Out[66]:
'51'
In [60]:
'1' + 2
Out[60]:
'12'
In [61]:
'5' * 20
Out[61]:
100
In [67]:
'5' * '5'
Out[67]:
25
In [68]:
't' * 5
Out[68]:
NaN
In [72]:
't' / null
Out[72]:
NaN
In [73]:
null == 0
Out[73]:
false
In [70]:
'8' / null
Out[70]:
Infinity

Variables & Scope

  • Variables should always be declared using the keyword var
    • Not necessary always, but easier than trying to remember when to use it and when not to
    • In strict mode is always necessary
  • The scope of a variable is the function it was declared in
    • Making a new function is currently the only way to make a new scope

Variables & Scope Examples

In [74]:
var a = 5
if(true)
    {
        var b = 6
    }
a + b
Out[74]:
11
In [80]:
var c = 6
function f() {
    var d = 11
}
c + d
Out[80]:
NaN

Conditionals & Looping

  • Javascript provides the following conditional statements
    • if
    • switch
  • And the following looping mechanisms
    • for
    • while
    • do-while
    • Array.forEach

If

  • The if statement in Javascript is pretty straightforward
    if (condition) {
      doSomething
    }
    
  • The parentheses are not necesary for a single line, but should always be used
  • if else looks like this:
    if (condition1){
    }
    else if(condition2){
    }
    else if(condition3){
    }
    else{
    }
    

Switch Statement

  • The syntax and mechanics of the swtich statement borrow heavily from other languages
  • Cases are marked with case and default provides a catch all case
    switch(toTest){
      case 1:
      case 2:
          doSomething
          break
      case "A":
      case "B":
          somethingElse
          break
      case "D":
          other
          break
      default:
          final
          break
      }
    

If and Switch Examples

In [82]:
var x = '0'
if(x < 0){
    console.log("Negative");
    }
//
/*
Note the triple equals

*/
else if(x === 0){
    console.log("Zero");
}
else{
    console.log("Positive");
}
Positive
Out[82]:
undefined
In [83]:
switch('0'){
    case -1:
        console.log("Negative")
        break
    case 0:
        console.log("Zero")
        break
    default:
        console.log("Positive")
        break
}
Positive
Out[83]:
undefined

Looping

  • The for loop construct is similar to other languages you know
    for(var i = 0; i < 10; i++){
    }
    
  • The while and do while syntax is also similar
    var i = 0
    while(i < 10){
      i++
    }
    

Looping Examples

In [90]:
for(var z = 0; z < 10; z++){
    console.log(z * z)
}
0
1
4
9
16
25
36
49
64
81
Out[90]:
undefined
In [87]:
var q = 1
while(q < 10){
    q++
}
Out[87]:
9

Functions

  • Functions in JavaScript are first class objects
  • They can be passed into and returned from other functions
    • This means closures are possible
  • To declare a function in JavaScript, the keyword is function
    function name(param1, param2, ...){
    }
    

Function Examples

In [91]:
square(10)

function square(x){
    return x*x
}
Out[91]:
100
In [92]:
function counter(){
    var count = 0;
    return function(){
        count++
        return count
    }
}
Out[92]:
undefined
In [93]:
var c = counter()
Out[93]:
undefined
In [102]:
c() + 1
Out[102]:
7