The difference between if (variable) and if (variable ==true) in JavaScript

Source: Internet
Author: User

if (judgment expression) {
Execute content
}

If the expression is true, the contents of the parentheses are executed.
Here, if the variable is not 0,null,undefined,false, it will be handled as true. As long as the variable has a value other than 0 or an object, an array, a string, it will be considered true
Variable ==true, the variable is a bool value, and is true before it is considered compliant.

var a;//defines a variable that is not initialized

if (a) {alert (1) return};//is not executed here, because a has no value, so is false;

a=0//here assigns a value of 0

if (a) {alert (1) return};//is executing this sentence because a=0;0 stands for false, so it is still not executed;

A=1 or a= "123";

if (a) {alert (1) return};//here a= the number except 0, or the character or obj is represented as true, the alert will execute!


var b;

if (b== "") and if (B==null) here who will execute it, of course, is the latter, because B is not defined value, if it is Var b= "", then the first one will be executed;

b = 1;

if (b==1) and if (b== "1") which one will be executed here, the answer is both will execute! Because JS = = = value is equal;


var C;

c=0;

if (C==false) will not execute it, the answer is yes;

C=1;

if (c==true) will do the same! But do we see the following?

c=2 or c= "admin"

if (c==true) alert (1) This sentence will be executed, the answer is no, because the default is that 0 is false and 1 is true, for the other is not so defined, so here will not execute, of course, if you are such if (c) then this will be executed!

The difference between if (variable) and if (variable ==true) in JavaScript

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.