Double exclamation mark in JavaScript (!!) Role

Source: Internet
Author: User

Often see such an example:
var A;
var b =!! A

A default is undefined.!a is true,!! A is false, so the value of B is false, not undefined, nor other values, mainly to facilitate subsequent judgments.

!! Generally used to cast the subsequent expression to a Boolean type of data (Boolean), which can only be true or false;
Because JavaScript is a weakly typed language (variables do not have a fixed data type), it is sometimes necessary to cast to the appropriate type, similar to the following:

A=parseint ("1234″")
A= "1234″-0//Convert to Digital
b=1234+ ""//Convert to String
C=someobject.tostring ()//Convert an object to a string
The 1th and 4th are explicit conversions, 2 and 3 are implicit conversions

Boolean conversions, JavaScript Convention rules are

False, undefinded, NULL, 0, "" is false
True, 1, "somestring", "[Object] is true"
The null and undefined other implicitly converted values, using the! Operator will produce true results, so the use of two exclamation points is to convert these values to "equivalent" Boolean value;
Take a look again:

var foo;
alert (!foo);//undifined case, an exclamation point returns true;
alert (!goo);//null case, an exclamation point returns true;
var o={flag:true};
var test=!! o.flag;//equivalent to Var test=o.flag| | False
alert (test);

This example demonstrates that when undifined and Null are returned with an exclamation point, the return is true, with two exclamation points returning the false, so the two exclamation point is that if the value of the variable is explicitly set (not null/undifined/0/"" equivalent), The result is returned based on the actual value of the variable, and if not set, the result returns false.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Double exclamation mark in JavaScript (!!) Role

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.