About the difference between js typeof and instanceof in judging data types and their development and use

About the difference between js typeof and instanceof in judging data types and their development and use

Preface:

In daily development, we often encounter situations where we need to determine the data type of a variable or whether the variable is null. How do you choose the operator to determine the type? This article summarizes and records the knowledge points about typeof and instanceof that our developers must master and the suggestions for their use in development. At the same time, such problems are often encountered during interviews.

1. typeof operator

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

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

Return Value

Meaning value

"undefined"

Undefined

"boolean"

Boolean

"string"

String

"number"

Numeric

"object"

An object (not a function) or null

"function"

function

"symbol"

symbol

(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 special objects such as Array and Null, typeof will always return object, which is the limitation of typeof console.log(typeof null); //'object'
        console.log(typeof [1, 2, 3]);//'object'
        console.log(typeof undefined); //'undefined'
        //Use the 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) You cannot use typeof to determine whether a variable exists

        var a;
        if (a === undefined) {
            console.log("variable does not exist")
        } else {
            console.log("variable exists")
        }
     // The variable does not exist

2. instanceof operator

While typeof is useful for primitive values, it is less useful for reference values. We usually don't care whether a value is an object, but rather what type of object it is. To solve this problem, ECMAScript provides the instanceof operator. Use as follows:

        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 instances of Object , so testing any reference value with instanceof operator and Object constructor will return true .

  • Similarly, if you use instanceof on a primitive value, it will always return false because primitive values ​​are not objects.

instanceof operator is used to determine whether prototype property of a constructor function appears anywhere in the prototype chain of an object. The implementation principle is as follows:

  function myInstanceof(left, right) {
    let proto = Object.getPrototypeOf(left), // Get the prototype of the object prototype = right.prototype; // Get the prototype object of the constructor function // Determine whether the prototype object of the constructor function is on the prototype chain of the object while (true) {
      if (!proto) return false;
      if (proto === prototype) return true;
      proto = Object.getPrototypeOf(proto);
    }
 }

3. The difference between typeof and instanceof and suggestions for use in development

Both typeof and instance 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.
  • 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.

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, it is recommended to use Object.prototype.toString and call this method to uniformly return a string in the format of “[object Xxx]” . Use as follows:

        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]"
 

Summarize:

This is the end of this article about the difference between js typeof and instanceof in judging data types and their development and use. For more relevant js typeof and instanceof content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Javascript basics loop
  • How to use async and await correctly in JS loops
  • Four data type judgment methods in JS
  • An example of elegant writing of judgment in JavaScript
  • How to convert a string into a number in JavaScript
  • parseInt parseFloat js string conversion number
  • JavaScript common statements loop, judgment, string to number

<<:  Solution to navicat automatically disconnecting from the database after a period of time

>>:  HTML tutorial, HTML default style

Recommend

Detailed explanation of MySQL file storage

What is a file system We know that storage engine...

7 cool dynamic website designs for inspiration

In the field of design, there are different desig...

CSS Tricks to Create Wave Effects

It has always been very difficult to achieve wave...

How to change the database data storage directory in MySQL

Preface The default database file of the MySQL da...

JS ES new features: Introduction to extension operators

1. Spread Operator The spread operator is three d...

MySQL password modification example detailed explanation

MySQL password modification example detailed expl...

How to optimize images to improve website performance

Table of contents Overview What is Image Compress...

NodeJS realizes image text segmentation

This article shares the specific code of NodeJS t...

InnoDB engine redo file maintenance method

If you want to adjust the size and number of Inno...

About React Native unable to link to the simulator

React Native can develop iOS and Android native a...

MySQL learning database search statement DQL Xiaobai chapter

Table of contents 1. Simple retrieval of data 2. ...