JavaScript Advanced Programming (v): JS keyword instanceof and typeof use

Source: Internet
Author: User

JavaScript instanceof and typeof are commonly used to determine whether a variable is empty, or what type it is. But there is a difference between them:

First, typeof

1, meaning: typeof returns a string of the data type of an expression, and returns the result as JS basic data type, including number,boolean,string,object,undefined,function. Syntax for typeof ( Data) or typeof data.

We can use TypeOf to get the existence of a variable, such as:

if (typeof a!='undefined') {alert ('ok ');}

It is best not to use if (a), because if a does not exist (undeclared) then it will go wrong, and for special objects such as Array,null, use TypeOf to return object, which is the limitation of TypeOf.

Second, instanceof

Instanceof to determine whether an object is a data type, or whether a variable is an instance of an object; Returns a Boolean type
The syntax is o instanceof A.

var o={};18alert ("H instanceof Person:" + (H instanceof person)); // true19alert ("H instanceof object:" + (H instanceof object)); // true20alert ("o instanceof object:" + (o instanceof object)); // true

JavaScript Advanced Programming (v): JS keyword instanceof and typeof use

Related Article

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.