In JavaScript, why (undefined && true) returns undefined?

Using the console node.js (node ​​0.10.24)

> var x = (undefined && true);
undefined
> x;
undefined
> x = (true && undefined);
undefined
> x;
undefined

Why does the comparison return undefined? I expect it to return false since undefined is considered "false".

+4
source share
4 answers

The statement &&internally coerces the expression values ​​to boolean, but the result of the statement is always the actual, inconsistent value of the first expression that failed (i.e. it was false).

Therefore, it (true && undefined)will result in undefined, because it is truenot false. Similarly, it (true && 0)will evaluate the value 0.

+7
source

javascript || && , .

a = b || c :

a = b ? b : c;

a = b && c :

a = b ? c : b;
//or
a = !b ? b : c;
+4

, , ECMAScript , :

  • lref LogicalANDExpression.
  • lval - GetValue (lref).
  • ToBoolean (lval) false, lval.
  • rref BitwiseORExpression.
  • GetValue (rref).

, , 11.11:

, && || Boolean. .

+3

, , - :

|| boolean && .

, ||, truthy, , , . falsy, , , falsy.

&&, falsy, , , truthy, , - .

0

Source: https://habr.com/ru/post/1534294/


All Articles