Graduate Program KB

Foundations of Javascript - Types and Coercion

Types

  • Variables don't have types, but the values don
    • You can have a variable 'X' that is assigned to a number type, but later you can assign a string to it.

NaN Value

  • Global property value that represents not a number
  • Used with Number.isNan(value) to check if a value is a number

new Keyword

  • Used to instantiate a new object that has a constructor.
    var testDate = new Date();
    var smallCar = new Car("small");

Coercion & Type Conversion

  • Coercion is implicit conversions of types.
  • Type Conversion can be implicit or explicit.
  • Implicit: "str" + 1, 1 is automatically converted to a string of "1"
  • Explicit: Number("0x11") "0x11" is being told to become a number.

Booleans

  • Falsy and Truthy, when converting values into booleans they become falsy and truthy.
  • Falsy Values;
    • Empty String
    • undefined
    • null
    • 0, -0,
    • NaN
    • False
  • Truthy Values;
    • Objects
    • Symbols
    • "populated string"
    • Numbers != 0 & -0
    • True
  • Condition statements and loops will implicitly convert condition into a boolean but is better to explicit state them
    if(array.length){} //When length is 0 then condition is false, implicit.
    if(array.length > 0) {} //Explicit, when length is greater than 0 then true.

Equality

  • == vs ===
    • ==, Checks if 2 operands value are equal.attempts to convert and compare operands of different types.
    • ===, Strict equality, checks values, but considers different operand types to be different
  • ==, Allows coercion (Different types)
  • ===, Doesn't allow coercion (Types need to be same)
    3 == '3' //True
    3 === '3' //False