Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the result of bool(true) && string is string in javascript?

Tags:

test code is:

console.log(true && "abc");//abc 

who can tell me why the result is abc?

like image 364
artwl Avatar asked Jul 18 '12 14:07

artwl


People also ask

Why Boolean is true?

Boolean. TRUE is a reference to an object of the class Boolean, while true is just a value of the primitive boolean type. Classes like Boolean are often called "wrapper classes", and are used when you need an object instead of a primitive type (for example, if you're storing it in a data structure).

Is a bool automatically true?

bool "bar" is by default true, but it should be false, it can not be initiliazied in the constructor. is there a way to init it as false without making it static?

Is bool One True or false?

Work with Booleans as binary values The byte's low-order bit is used to represent its value. A value of 1 represents true ; a value of 0 represents false .

What is the result of bool false )?

It can return one of the two values. It returns True if the parameter or value passed is True. It returns False if the parameter or value passed is False.


2 Answers

From MDN (Logical Operators) - Logical And (&&):

Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

true obviously cannot be evaluated to false, so the second value is returned which is "abc".

like image 72
Justin Niessner Avatar answered Dec 04 '22 19:12

Justin Niessner


The && operator in JavaScript is somewhat different than in C or Java or etc. It always returns the last evaluated subexpression value (whether the overall expression is true — "truthy" — or false — "falsy") and doesn't force a boolean result. When it fails (when one of the values is "falsy"), then similarly the result is the raw value, and not the value's boolean interpretation.

So it's like this: given A && B, the interpreter does the following:

  1. Evaluate expression A, giving AV — the value of A
  2. Let AB be the result of casting AV to boolean
  3. If AB is false, then the value of the && expression is AV
  4. Evaluate expression B, giving BV
  5. Return BV as the value of the && expression.

Thus in an if statement, the && expression has the same effect as the boolean-casting operators in C or Java, because the if statement itself performs a truthy/falsy test on the overall result of the expression. When used by itself however, it's more like, "give me the value of the second expression if it the first is truthy, otherwise give me the value of the first expression".

like image 38
Pointy Avatar answered Dec 04 '22 17:12

Pointy