Summary of differences between typeof and instanceof in JS

Source: Internet
Author: User

In JavaScript, typeof and instanceof are often used to determine whether a variable is null or of any type. But there is a difference between them:

Typeof

Typeof is a one-dimensional operation. Before a single operation, the operation can be of any type.

The return value is a string that represents the type of the number of operations. Typeof generally only returns the following results:

Number, boolean, string, function, object, undefined. We can use typeof to obtain whether a variable exists, such as if (typeof! = "Undefined") {alert ("OK")}, instead of using if (a) because if a does not exist (not declared), an error will occur. For Array, null and other special objects use typeof to return all objects, which is the limitation of typeof.

Instanceof

Instance: instance, for example

A instanceof B? Alert ("true"): alert ("false"); // is a B instance? True: false

Instanceof is an instance used to determine whether a variable is an object, such as var a = new Array (); alert (a instanceof Array );
True is returned, and true is returned for alert (a instanceof Object). This is because Array is an object.
. For example, function test () {}; var a = new test (); alert (a instanceof test) will return

When talking about instanceof, We need to insert another question, that is, function arguments. We may all think that arguments is
Array, but if you use instaceof for testing, you will find that arguments is not an Array object, although it looks like a lot.

In addition:

Test var a = new Array (); if (a instanceof Object) alert ('y'); else alert ('n ');

Get 'y'

However, if (window instanceof Object) alert ('y'); else alert ('n ');

'N'

Therefore, the instanceof object here refers to the object in js syntax, not the dom model object.

There are some differences when typeof is used.

Alert (typeof (window) will get the object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.