Differences between the "typeof" operator and the "instanceof" operator in JavaScript

Source: Internet
Author: User

In javascript, the operators "typeof" and "instanceof" can be used to determine the type of data, so what are the differences between the two operators?

Difference one: use different ways.

The most obvious difference is the way these two operators are Used. "typeof" is a unary operator followed directly by the data that needs to be typed, whereas "instanceof" is a two-tuple operator whose left side is the data to be judged, and the right is the type for Comparison.

typeof is a unary operator; var amount = 108;console.log (typeof amout);//console output "number";//instanceof is a two-dollar operator; var name = new String (' Jim '); console.log (name instanceof String);//console output "true";

Difference Two: the Action object is Different.

The operator "typeof" can be used either for raw type data or for reference to type data, while the operator "instanceof" can only be used to determine the specific type of reference type Data.

Difference Three: The return value differs when acting on a reference value.

  When used as a reference value, the return value of the operator "typeof" is only "object" or "function", and the type of the data cannot be accurately judged. In contrast, the operator "instanceof" can be used to accurately determine the type of Data.

Acting on the reference value, the "typeof" return value is only object or function;var name = new String (' Jim '), var remind = function () {  alert (' don ' t forget! ');       }console.log (typeof name);//console output "Object", console.log (typeof remind);//console output "function"; console.log (name instanceof String);//console Output "true";

Differences between the "typeof" operator and the "instanceof" operator in JavaScript

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.