开发者

Could you explain these two javascript examples?

1: Why is the result of foo && baz not 1? Because true is 1.

开发者_如何学运维
var foo = 1;
var baz = 2;

foo && baz;   // returns 2, which is true

2: There are two pluses in the console.log(foo + +bar);, what's the meaning of them?

var foo = 1;
var bar = '2';
console.log(foo + +bar);


That's because the && (logical AND) operator returns the value of the last operand it evaluated. Since foo is true, it has to evaluate bar to determine the outcome of the expression (it will only be true if bar is also true).

The opposite would happen with the || (logical OR) operator. In that case, since foo is true, the outcome of the expression is known to be true without having to evaluate bar, so the value of foo will be returned.

Concerning your second question, the unary + operator allows to convert the string '2' into the number 2.


&& returns the value of the last evaluated value. ´&&´ is a operator. Most of the time it used in a context like this

if ( something && somethingelse ) {}

in other words

0 && 2 //would return 0 because 0 is a falsy value
12 && 10 && 0 && 100 // would return 0 to 
10 && 123 && "abc" // returns "abc"

+ is a mathematical operator but it can be used to convert a string in to a number.

1 + 1 = 2
1 + '1' = 11 //van damme would like this one
1 + +'1' = 2 // somce '1' got converted to a number


Javascript follows Short Circuit Evaluation. So according to this, javascript returns the last value if both the values are true

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜