Type Checking

typeof Operator

The 'typeof' operator returns the type of the argument as a string.
It can also be used with parentheses like a function.

typeof 10            // "number" 
typeof(20) // "number"
typeof Number(100) // "number"
typeof new Number(100) // "object"
typeof 0 // "number"
typeof Infinity // "number"
typeof true // "boolean"
typeof new Boolean(true) // "object"
typeof "text" // "string"
typeof "" // "string"
typeof Symbol("id") // "symbol"
typeof [] // "object"
typeof Array(5) // "object"
typeof Math // "object"
typeof alert // "function"
typeof undefined // "undefined"
typeof NaN // "number"
typeof null // "object"
typeof new Date // "object"
typeof new RegExp("^(.+)$") // "object"
typeof new Object // "object"
typeof {} // "object"
typeof function() {} // "function"
typeof new Function // "function"

The let or const keywords will still throw a ReferenceError if they are used with the typeof operator before they are initialized

console.log(typeof myUndeclaredVariable === 'undefined');  

instanceof Operator

The 'instanceof' operator returns a boolean of whether the value matches a specific data type.
Checks whether the variables was created from a specific Instance Constructor type.
Lets you check if an object has a specific object type.

const myString1 = new String("Mon"); 
myString1 instanceof String; // true
const myString2 = "Mon";
myString2 instanceof String; // false - because we used a literal string

const myNumber1 = new Number(100);
myNumber1 instanceof Number; // true
const myNumber2 = 100
myNumber2 instanceof Number; // false - because we used a literal number

const myBoolean1 = new Boolean(true);
myBoolean1 instanceof Boolean; // true
const myBoolean2 = true;
myBoolean2 instanceof Boolean; // false - because we used a literal boolean

const myArray = [ "one", two"];
myArray instanceof Array // true

const myObject = { property1: "hello", property2: "world" };
myObject instanceof Object // true

const myFunction = function myFunc() { return "text"; }
myFunction instanceof Function // true

© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext