shubham choudhary
shubham choudhary

Reputation: 3120

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

Upvotes: 1

Views: 56

Answers (2)

xianshenglu
xianshenglu

Reputation: 5329

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

Upvotes: 2

JDSchenck
JDSchenck

Reputation: 326

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.

Upvotes: 2

Related Questions