Skip to content

Instantly share code, notes, and snippets.

@fabriciofmsilva
Last active February 17, 2018 12:52
Show Gist options
  • Save fabriciofmsilva/afab8e148ed10e34c02e329ebec5fa31 to your computer and use it in GitHub Desktop.
Save fabriciofmsilva/afab8e148ed10e34c02e329ebec5fa31 to your computer and use it in GitHub Desktop.
Checking Types in Javascript

Checking Types in Javascript

typeof

typeof 3; // "number"
typeof 'abc'; // "string"
typeof {}; // "object"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof function(){}; // "function"

typeof null; // "object"
typeof [1, 2, 3]; // "object"

instanceof operator

function Animal(){}
var a = new Animal()
a instanceof Animal // true

a.constructor === Animal // true

function Cat(){}
Cat.prototype = new Animal
Cat.prototype.constructor = Cat
var felix = new Cat
felix instanceof Cat // true
felix instanceof Animal // true
felix.constructor === Cat // true
felix.constructor === Animal // false

felix = null
felix instanceof Animal // true
felix.constructor === Animal // throws TypeError

[1, 2, 3] instanceof Array // true
/abc/ instanceof RegExp // true
({}) instanceof Object // true
(function(){}) instanceof Function // true

3 instanceof Number // false
true instanceof Boolean // false
'abc' instanceof String // false

null instanceof Boolean // false
undefined instanceof Array // false

(3).constructor === Number // true
true.constructor === Boolean // true
'abc'.constructor === String // true

var wrapper = new Number(3)

new Number(3) instanceof Number // true
new Boolean(true) instanceof Boolean // true
new String('abc') instanceof String // true

Cross-window Issues of instanceof

Duck-Typing

Object.prototype.toString method

function is(obj) {
  return Object.prototype.toString.call(obj);
}

function isArray(obj) {
  return is(obj) === '[object Array]';
}

function isObject(obj) {
  return is(obj) === '[object Object]';
}

function isFunction(obj) {
  return is(obj) === '[object Function]';
}

function isNumber(obj) {
  return is(obj) === '[object Number]';
}

Function.prototype.toString method

DOM Elements and Host Objects

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment