Even a novice can understand the difference between typeof and instanceof in js

Even a novice can understand the difference between typeof and instanceof in js

1. typeof

The typeof operator returns a string indicating the type of its unevaluated operand. It is used as follows:

typeof operand
typeof(operand)

operand is an expression representing an object or primitive value, the type of which will be returned. For example

typeof 1 // 'number'
typeof '1' // 'string'
typeof undefined // 'undefined'
typeof true // 'boolean'
typeof Symbol() // 'symbol'
typeof null // 'object'
typeof [] // 'object'
typeof {} // 'object'
typeof console // 'object'
typeof console.log // 'function'

From the above example, the first 6 are basic data types. Although typeof null is object, this is just a long-standing bug in JavaScript. It does not mean that null is a reference data type, and null itself is not an object.

Therefore, the result returned by null after typeof is problematic and cannot be used as a method to determine null. If you need to check whether it is null in an if statement, just use ===null to check.

At the same time, you can find the reference type data. If you use typeof to judge, except for function, the rest will output object
If we want to determine whether a variable exists, we can use typeof: (if(a) cannot be used, as it will result in an error if a is not declared)

if(typeof a != 'undefined'){
    //Variable exists}

2. instanceof

The instanceof operator is used to detect whether the prototype property of a constructor function appears in the prototype chain of an instance object. It is used as follows:

object instanceof constructor

object is the instance object, constructor is the constructor function. The constructor function can instantiate an object through new, and instanceof can determine whether this object is the object generated by the previous constructor.

// Define the construction function let Car = function() {}
let benz = new Car()
benz instanceof Car // true
let car = new String('xxx')
car instanceof String // true
let str = 'xxx'
str instanceof String // false

Regarding the implementation principle of instanceof, please refer to the following:

function myInstanceof(left, right) {
    // Here we use typeof to determine the basic data type. If it is, return false directly
    if(typeof left !== 'object' || left === null) return false;
    // getProtypeOf is the API of the Object object, which can get the prototype object of the parameter let proto = Object.getPrototypeOf(left);
    while(true) {                  
        if(proto === null) return false;
        if(proto === right.prototype) return true; //Find the same prototype object and return true
        proto = Object.getPrototypeof(proto);
    }
}

That is, follow the prototype chain until the same prototype object is found and return true, otherwise false

3. Difference

Both typeof and instanceof are methods for determining data types. The differences are as follows:

  • typeof returns the basic type of a variable, instanceof returns a Boolean value
  • instanceof can accurately determine complex reference data types, but cannot correctly determine basic data types
  • However, typeof also has its drawbacks. Although it can determine the basic data type (except null), it cannot determine the reference data type except the function type.

1. For objects, arrays, and null, the returned value is object. For example, the values ​​returned by typeof(window), typeof(document), and typeof(null) are all objects.
2. For function types, the returned value is function. For example: the values ​​returned by typeof(eval) and typeof(Date) are both functions.

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

If you need to detect data types in general, you can use Object.prototype.toString and call this method to return a string in the format of "[object Xxx]" as follows

Object.prototype.toString({}) // "[object Object]"
Object.prototype.toString.call({}) // Same result as above, plus call is also OK
Object.prototype.toString.call(1) // "[object Number]"
Object.prototype.toString.call('1') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(function(){}) // "[object Function]"
Object.prototype.toString.call(null) //"[object Null]"
Object.prototype.toString.call(undefined) //"[object Undefined]"
Object.prototype.toString.call(/123/g) //"[object RegExp]"
Object.prototype.toString.call(new Date()) //"[object Date]"
Object.prototype.toString.call([]) //"[object Array]"
Object.prototype.toString.call(document) //"[object HTMLDocument]"
Object.prototype.toString.call(window) //"[object Window]"

Now that we know the basic usage of toString, let's implement a global data type judgment method.

function getType(obj){
  let type = typeof obj;
  if (type !== "object") { // Perform typeof judgment first. If it is a basic data type, return return type directly;
  }
  // For typeof, the result is object. Then make the following judgment. The regular result is return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1'); 
}

Use as follows

getType([]) // "Array" typeof [] is object, so toString returns getType('123') // "string" typeof directly returns getType(window) // "Window" toString returns getType(null) // "Null" has its first letter capitalized, typeof null is object, so toString is needed to determine getType(undefined) // "undefined" typeof directly returns getType() // "undefined" typeof directly returns getType(function(){}) // "function" typeof can determine, so the first letter is lowercase getType(/123/g) //"RegExp" toString returns

This is the end of this article about how even novices can understand the difference between typeof and instanceof in js. For more information about typeof and instanceof in js, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of typeof and instanceof usage in JavaScript
  • Difference between Javascript typeof and instanceof
  • JavaScript type detection: defects and optimization of typeof and instanceof
  • Talk about my in-depth understanding of typeof and instanceof in JavaScript
  • A brief discussion on instanceof and typeof in javascript
  • Detailed analysis of the usage and differences of instanceof and typeof operators in JavaScript
  • Summary of the difference between typeof and instanceof in JS
  • About the difference between js typeof and instanceof in judging data types and their development and use

<<:  Zabbix monitors Linux hosts based on snmp

>>:  Detailed tutorial on how to install OpenStack Ussuri in CentOS8 with minimal deployment

Recommend

A super detailed Vue-Router step-by-step tutorial

Table of contents 1. router-view 2. router-link 3...

Steps to build a Docker image using Dockerfile

Dockerfile is a text file that contains instructi...

Docker Nginx container production and deployment implementation method

Quick Start 1. Find the nginx image on Docker Hub...

Can asynchrony in JavaScript save await?

I knew before that to synchronously obtain the re...

MariaDB under Linux starts with the root user (recommended)

Recently, due to the need to test security produc...

Common considerations for building a Hadoop 3.2.0 cluster

One port changes In version 3.2.0, the namenode p...

Detailed explanation of CSS3 animation and new features of HTML5

1. CSS3 animation ☺CSS3 animations are much easie...

HTML page jump passing parameter problem

The effect is as follows: a page After clicking t...

Solve the problem that Mysql5.7.17 fails to install and start under Windows

Install MySQL for the first time on your machine....

Detailed explanation of JS ES6 coding standards

Table of contents 1. Block scope 1.1. let replace...

Example code for using @media in CSS3 to achieve web page adaptation

Nowadays, the screen resolution of computer monit...