Home >Web Front-end >JS Tutorial >What is the difference between typeof and instanceof

What is the difference between typeof and instanceof

王林
王林Original
2020-11-13 10:51:4018330browse

The difference between typeof and instanceof is: the return value of typeof is a string, used to describe the data type of the variable; the return value of instanceof is a Boolean value, used to determine whether a variable belongs to an instance of an object .

What is the difference between typeof and instanceof

Compare typeof and instanceof

Same points:

typeof and instanceof in JavaScript are often used to determine whether a variable is empty , or what type it is.

(Learning video recommendation: javascript video tutorial)

Differences:

typeof:

1. The return value is one String used to describe the data type of the variable.

2. Typeof generally can only return the following results: number, boolean, string, function, object, undefined.

 if (typeof a != "undefined") {
   console.log("ok");

 } eles {
    console.log("not ok");
}
//下面的代码是错误的
// if (a) //因为如果 a 不存在( 未声明) 则会出错。
// if (a) {
//     console.log("ok");

// } else {
//     console.log('cc');

// }

Using typeof for special objects such as Array and Null will always return object. This is the limitation of typeof.

instanceof:

1. The return value is a Boolean value

2. Instanceof is used to determine whether a variable belongs to an instance of an object.

// var a = new Array();
// alert(a instanceof Array); // true
// alert(a instanceof Object) // true
//如上, 会返回 true, 同时 alert(a instanceof Object) 也会返回 true;
// 这是因为 Array 是 object 的子类。
// alert(b instanceof Array) // b is not defined

// function Test() {};
// var a = new test();
// alert(a instanceof test) // true

Related recommendations: js tutorial

The above is the detailed content of What is the difference between typeof and instanceof. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn