Javascript

Types and Grammar

Contents

  • Types
  • Values
  • Natives
  • Coercion
  • Grammar

Types (again!?)

  • null
  • undefined
  • boolean
  • number
  • string
  • object
  • symbol (ES6)

typeof foo(){...} == "function"

BUT

functions are callable objects

Values as Types

  • vales has types
  • variables don't have types
  • no static typing
var a = 5;
typeof a; // "number"

a = "different value";
typeof a // "string"

undefined vs undeclared

var x;

x; // undefined
y; // ReferenceError: y is not defined

WTF: type of undeclared variable is undefined

var x;

typeof x; // "undefined"
typeof y; // "undefined"

Values

  • Arrays
    • store any types
    • object with additional prototype methods
  • Array-likes
    • List of DOM elements
    • Cannot use Array.prototype methods
  • string
    • like Array of character but not every Array methods work
    • immutable
  • number
    • no distinction between integer and float

Numbers

  • NaN
  • Infinity / -Infinity
  • -0 / 0

value vs reference

  • number, string, boolean are copied by value (immutable)
  • Arrays, objects are copied by reference (mutable)

Natives

  • String( )
  • Number()
  • Boolean()
  • Array()
  • Object()
  • Function()
  • RegExp()
  • Date()
  • Error()
  • Symbol()

Boxing

Primitives can use methods of natives

Unboxing

Getting underlying primitive from natives

var a = 'abc'

a.length; // 3
a.toUpperCase(); // "ABC"
var a = new String('abc');

a; // [String: 'abc']
a.valueOf(); // "abc"

Avoid natives if there's no reason to use

  • {} instead of new Object()
  • function foo () {...} instead of new Function("foo", "...")
  • [] instead of new Array()

Coercion

  • Implicit type conversion 
  • type casting: explicit type conversion
  • Coercion is ended with primitives 
  • toString, toBoolean, toNumber
  • loose equality (==) uses coercion

Grammar

  • {..} => object or block scope
  • if / else if / else
  • Operator precedence
  • Automatic semicolon insertion (ASI)
  • try, catch, finally
  • switch

Keep coding Javascript...

Javascript - Types & Grammar

By Özgün Bal

Javascript - Types & Grammar

  • 88