• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The ECMAScript specification defines seven data types, divided into basic and reference types. Let’s explore how these two types are distinguished.

Basic type: String Number Boolean Undefined Null Symbol Reference type: Object

  1. typeof

Typeof follows a unary expression to the right and returns the result as the expression’s data type (string).

// The following data types can be used to make the correct judgment
typeof ' ' // string
typeof 100  // number
typeof Symble('100') // symbol
typeof true // boolean
typeof undefined // undefined
typeof new Function(a)// function

// The following data types cannot be correctly judged
typeof null // object
typeof ['100'] // object
typeof new Date(a)// object
typeof new RegExp(a)// object
Copy the code

As you can see from the above example, Typeof is better suited for handling basic data types, returning the correct result except for null, which returns type Object.

  1. instanceof

Instanceof returns true if A is an instanceof B, false otherwise. Note: Instanceof tests prototypes. When A’s __proto__ points to B’s prototype, A is judged to be an instance of B.

[] instanceof Array // true
[] instanceof Object // true

{} instanceof Object // true

new Date(a)instanceof Date // true
new Date(a)instanceof Object // true

function Animal() {}
new Animal() instanceof Animal // true
new Animal() instanceof Object // true
Copy the code

Taking [] as an example, it can be judged that [] is both an instanceof Array and an instanceof Object by instanceof, from which it can be seen that instanceof detects a prototype. The relationship between them is as follows: [].__proto__ points to array. prototype, array.prototype. __proto__ points to object. prototype, object.prototype. __proto__ points to null, This is the end of such a chain of prototypes. [].__proto__ -> array.proto__ -> object.proto__ -> null It is not possible to determine what type an object instance belongs to.

  1. toString

Calling toString() directly on Object objects returns [Object, Object] by default. For other objects, calls to call call/apply return the correct type information.

Object.prototype.toString.call(' ') // [object String]
Object.prototype.toString.call(true) // [object Boolean]
Object.prototype.toString.call(1) // [object Number]
Object.prototype.toString.call(Symbol()) // [object Symbol]
Object.prototype.toString.call(undefined) // [object Undefined]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(new Function()) // [object Function]
Object.prototype.toString.call([]) // [object Array]
Copy the code