JavaScript typeof operator Usage Examples _ basics

Source: Internet
Author: User
Tags numeric value

Using the typeof operator on a value may return one of the following strings:
"Undefined"--if this value is not defined
"Boolean"--if this value is a Boolean value
"String"--if this value is a string
"Number"--if this is a numeric value
"Object"--if this is an object or null
"Function"--if this value is a function

The return values of the commonly used typeof operators include number, String, Boolean, Undefined, object, and function. Such as:

Copy Code code as follows:

var n;
Console.log (typeof N); "Undefined"

n = 1;
Console.log (typeof N); "Number"

n = "1";
Console.log (typeof N); "String"

n = false;
Console.log (typeof N); "Boolean"

n = {name: "obj"};
Console.log (typeof N); "Object"

n = new number (5);
Console.log (typeof N); "Object"

n = function () {return;};
Console.log (typeof N); "Function"

These examples show that the operands of the typeof operator can be either a variable (message) or a numeric literal. Note that TypeOf is an operator rather than a function, so the parentheses in the example are not required (although they can be used).


From the example above, we find that numbers created with number () are also returned with the value "Object" by TypeOf as objects, because constructors return objects, so if we want to distinguish between numeric objects (number), String objects (String), What if you have an array object (array), a function object, a Date object (date), a Boolean object (Boolean), and a JavaScript built-in object such as an Error object (Error)? Here you can call the object's ToString method, such as:

Copy Code code as follows:

var n, Res;

n = new number (66);
res = Object.prototype.toString.call (n);
Console.log (RES); "[Object number]"

n = new String ("string");
res = Object.prototype.toString.call (n);
Console.log (RES); "[Object String]"

n = [];
res = Object.prototype.toString.call (n);
Console.log (RES); "[Object Array]"

// ...

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.