Datatypes

  • Primitive:
    • string (defined using quotes: " or ')
    • number (always double datatype: 64-bit floating point)
    • bigint (introduced recently for even bigger numbers)
    • boolean (true or false)
    • undefined (variables which are declared but not initialized, it represents emptiness)
    • null (explicitly telling null)
    • Symbol (used to define unique objects)
  • Object
    • An Object (under {...}) — Top level class Object
    • An Array (under [...])
    • primitive datatype wrappers: Number, String, Boolean, BigInt (please avoid using them)
    • In built classes objects: RegExp, Date etc.
    • Math class has static properties and functions which are useful but it cannot be instantiated

Determine the datatype

  • typeof operator can be used for all primitive types except null to find the type of javascript variable.
typeof "John"         // Returns "string"
typeof 3.14           // Returns "number"
  • instanceOf can be used to detect reference types
  • It internally works by testing if the right operand appears anywhere in the prototype chain of the left.
function Person() {
    this.name = 'KK';
}
 
var person = new Person();
 
console.log(person instanceof Person); // true
console.log(person instanceof Object); // true
console.log([1,2,3] instanceof Array); // true
console.log('abc' instanceof String); // false since 'abc' is primitive and not object of String
console.log(new String('abc') instanceof String); // true
  • Checking Array can also be done using Array.isArray() but it fails across iframe (rare scenario)
const arr = [1,2,3];
console.log(Array.isArray(arr)); // true

Primitive methods

  • Primitive datatypes can have methods which can be called
  • To achieve this JS creates a wrapper function before calling the method
let str = "Hello";
alert( str.toUpperCase() ); // HELLO
  • For each primitive we have wrapper class like String for string. So a wrapper object is created for str and then toUpperCase() method is called. After JS is done calling the method the wrapper class object is destroyed

Number() vs new Number()

  • Always avoid creating a primitive using wrapper class constructor.
    • var x = new Number() is highly discouraged and will cause x to be an object instead of primitive
  • Corresponding function without invoking constructor is fine since it helps in converting primitive
    • var x = Number('123') is perfectly fine and x will be number primitive here

Host vs Native objects

  • Native Objects: part of core JS engine:
    • String, Math, RegExp, Object, Function
  • Host objects: Provided by runtime environment:
    • window, XMLHttpRequest