On the Difference and Development of js typeof and instanceof Judgement Data Types

  • 2021-11-29 06:09:13
  • OfStack

Directory 1, typeof Operator 2, instanceof Operator 3, typeof, and instanceof Differences and Suggestions for Use in Development


In daily development, we often encounter the situation of judging the data type of a variable or whether the variable is null. How do you choose the operator to judge the type? This article summarizes what we developers must master about Record 1 typeof And instanceof Knowledge points and suggestions for use in development, and often encounter such problems in the interview process.

1. typeof Operator

typeof Operator to determine the data type of any variable, specifically, it is the best way to determine whether a variable is a string, numeric value, Boolean value or undefined. Its return value is of string type and is used as follows: typeof Is an operator, not a function, but you can pass variables as parameters:
a、typeof  operand
b、typeof (operand)

(1) The return value is of string type, where:












对象(而不是函数)或 null





(2) Common usage methods

        console.log(typeof undefined);//'undefined'
        console.log(typeof true);//'bpplean'
        console.log(typeof ("number"));  //'string'
        console.log(typeof "number");  //'string' 
        console.log(typeof 1);//'number'
        console.log(typeof Symbol());//'symbol'
        // For Array , Null And other special objects use typeof1 Rhythm return object , this is exactly typeof Limitations of 
        console.log(typeof null);   //'object'
        console.log(typeof [1, 2, 3]);//'object'
        console.log(typeof undefined);  //'undefined'
        // Pass  typeof  Operator to distinguish functions from other objects 
        function f1() { console.log(111); }
        console.log(typeof f1);  //'function'  
        console.log(typeof f1());  // 111 'undefined'

(3) The existence of a variable cannot be judged by typeof

        var a;
        if (a === undefined) {
            console.log(" Variable does not exist ")
        } else {
            console.log(" Existence of variables ")
       //  Variable does not exist 

2. instanceof operator

typeof Although useful for raw values, it is of little use for referenced values. We usually don't care if a value is an object, but we want to know what kind of object it is. To solve this problem, ECMAScript Provides instanceof Operator. Use the following:

        function f1() { console.log(111); }
        console.log(f1 instanceof Object);//true
        console.log(f1 instanceof Function);//true
        console.log(f1 instanceof RegExp);//false

All reference values are Object Instance of, so pass the instanceof Operator detects any reference value and Object Constructor returns true .

Similarly, if you use the instanceof Is detected, the original value is always returned false Because the original value is not an object.

instanceof Operator is used to determine the prototype Property appears anywhere in the prototype chain of the object. Its implementation principle is as follows:

  function myInstanceof(left, right) {
    let proto = Object.getPrototypeOf(left), //  Get the prototype of the object 
    prototype = right.prototype; //  Object of the constructor  prototype  Object 

  //  Determines the constructor's  prototype  Whether the object is on the prototype chain of the object 
    while (true) {
      if (!proto) return false;
      if (proto === prototype) return true;
      proto = Object.getPrototypeOf(proto);

3. Differences between typeof and instanceof and suggestions for use in development

typeof And instance They are all methods to judge data types, with the following differences:

typeof Returns the basic type of 1 variable, instanceof Returns 1 Boolean value instanceof It can accurately judge the complex reference data type, but it can't correctly judge the basic data type And typeof There are drawbacks, although it can judge the underlying data type ( null Except for the reference data type, but in the reference data type, except for the function Other than the type, other things can't be judged

It can be seen that the above two methods have drawbacks and cannot meet the needs of all scenarios

If a common test data type is required, it is recommended to use Object.prototype.toString This method is called, and the format is returned by unified 1 “[object Xxx]” The string of the. Use the following:

        console.log(Object.prototype.toString.call(undefined))  //"[object Undefined]"
        console.log(Object.prototype.toString.call(true))  // "[object Boolean]"
        console.log(Object.prototype.toString.call('1'))  // "[object String]"
        console.log(Object.prototype.toString.call(1))    // "[object Number]"
        console.log(Object.prototype.toString.call(Symbol()))    // "[object Symbol]"
        console.log(Object.prototype.toString.call({}))   // "[object Object]"
        console.log(Object.prototype.toString.call(function () { }))   // "[object Function]"
        console.log(Object.prototype.toString.call([]))       //"[object Array]"
        console.log(Object.prototype.toString.call(null))    //"[object Null]"
        console.log(Object.prototype.toString.call(/123/g))     //"[object RegExp]"
        console.log(Object.prototype.toString.call(new Date()))  //"[object Date]"


Related articles: