简体   繁体   中英

why this code is not working as expected?

let x;
console.log("shubham" == true );  // gives false
"shubham" ? x=2 : x=3;
console.log(x); // gives 2, so "shubham" must be true?  

//I am hoping to get value 3

when you use this:

"shubham" == true

before comparing, true turned to 1,so the actually comparsion is

"shubham" == 1

so ,it gives false;

the book:

When performing conversions, the equal and not-equal operators follow these basic rules:

If an operand is a Boolean value, convert it into a numeric value before checking for equality. A value of false converts to 0, whereas a value of true converts to 1.

If one operand is a string and the other is a number, attempt to convert the string into a number before checking for equality.

when you use this:

"shubham" ? x=2 : x=3;

works like:

Boolean("shubham")?x=2:x=3

so,it gives you x=2;

the book:

variable = boolean_expression ? true_value : false_value;

This basically allows a conditional assignment to a variable depending on the evaluation of the boolean_expression. If it's true, then true_value is assigned to the variable; if it's false, then false_value is assigned to the variable.

the book:

Professional JavaScript for Web Developers.3rd.Edition.Jan.2012

Yes, this is due to the underlying code behind the 'if' statement in Javascript. It relies on a method 'ToBoolean' which converts the condition of the if statement to a boolean value. Any string that is not empty, is converted to true. Thus, why you get the above logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM