3-19 Types and javascript

bigword alert : Dynamic typing

  • you don’t tell the engine what type of data a variable holds
  • it figures it out while your code is running

3-20 Primitive types

bigword alert : Primitive type

  • a type of data that represents a single value
  • (not a object)

List of primitive types in javascript

  1. undefined
    lack of existence(note that you shouldn’t set avariable to this)

  2. null
    lack of existence(you can set a variable to this)

  3. boolean
    true or false

  4. number
    floating point number

  5. string
    sequence of characters

  6. symbol
    new feature in ES6, 略

3-21 Operators

bigword alert : operator

  • a special function that is syntactically (written) differently
add operator
1
2

var a = 4 + 3;
  • recall : postfix, prefix, infix

3-22 Operator precedence and associativity

operator precedence and Associativity table

bigword alert : operator precedence

  • which operator function get called first
  • higer precedence wins

bigword alert : associativity

  • when function have the same precedence, what order operator function get called in
  • left-to-right or right-to-left
precedence and associativity
1
2
3
4
5
6
7

var a = 4 + 3 * 5;
// precedence

var b = 4, var c = 5;
a = b = c;
// associativity

3-24 Coercion

bigword alert : Coercion

  • converting a value from one type to another
Coercion
1
2
3
4
5
6
7

var a = 1
var b = '2';

/* bunch of codes */

console.log(a+b);

3-25 Comparison operator

Comparsion result table

  • Recalls : associativity, operator, coercion
try it out
1
2
3
4
5
6
7
8
9
10
11
12
13

console.log(3 < 2 < 1);

/*
3 < 2 < 1 //associativity
false < 1 //coercion
0 < 1 //operator
true

*/

Number(undefined) // NaN
Number(null) // 0
weird equal operator
1
2
3
4
5
6

'3' == 3 //true
false == 0 //true
null == 0 //false, what!?
"" == 0 //true
"" == false //true
  • In javascript, == will do coercion
  • Strict equality (===) is going to save your life !!
  • 99% of the time, use ===

3-27 Existence adn Booleans

how coercion could be useful
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Boolean(undefined); //false
Boolean(null); //false
Boolean(''); //false
Boolean(0) //false
var a;

/*goes internet and looks for a value*/

// a is coercion to boolean
// if a could be 0, addtional comparsion is need
if (a || a === 0){
console.log('Something is there.');
}