Tips the difference between the instanceof operator and the typeof operator

Source: Internet
Author: User

Tips the difference between the instanceof operator and the typeof operator

One, instanceof operators:
This operator can determine whether a variable is an instance of an object (class), and the return value is of type Boolean (True and false).
To understand its role, an object-oriented understanding must be understood:
The code example is as follows:

var str=new String ("Foodoir"); var str2= "Foodoir";  Console.log (str instanceof String); Trueconsole.log (str2 instanceof String);//false

The above code will output true because STR is an object instance of the object string.
In general, only objects created with the constructor will return true, otherwise false, but the array is an exception and will return true.

var arr = [1,2,3];var arr2 = new Array, Console.log (str instanceof string);//trueconsole.log (str instanceof string) ;//true


Second, typeof operator:
This operator can return a string that describes the type of the meta-arithmetic, and its return value can be as follows:
number,boolean,string,function,object,undefined

The instance code is as follows:

    var str=new String ("Foodoir");    var str2= "Foodoir";      Console.log (typeof str);  Object    Console.log (typeof str2); String

In the above code, the first one can output the exact type "object", which is not accurate; the second one is "string".
Generally speaking, the operation using typeof is a direct volume, which returns the exact result, if the object created with the constructor returns "Object", but is an exception to the array, which returns "object" whether or not it is a direct quantity.

    var arr = [n/a];    var = new Array (ARR2);    Console.log (typeof arr);    Console.log (typeof arr2);

Tips the difference between the instanceof operator and the typeof operator

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.