Could you explain these two javascript examples? - Stack Overflow

1: Why is the result of foo && baz not 1? Because true is 1.var foo = 1;var baz = 2;foo &&

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);

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);
Share Improve this question edited Jun 24, 2011 at 12:00 Lombo 12.2k2 gold badges23 silver badges28 bronze badges asked Jun 24, 2011 at 11:53 runeverydayruneveryday 2,7994 gold badges32 silver badges44 bronze badges 2
  • These are two very separate questions, probably should be separated. – Orbling Commented Jun 24, 2011 at 11:55
  • 5 This is javascript not jQuery. – Jazaret Commented Jun 24, 2011 at 11:55
Add a ment  | 

3 Answers 3

Reset to default 10

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 oute 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 oute 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745379687a4625165.html

相关推荐

  • Could you explain these two javascript examples? - Stack Overflow

    1: Why is the result of foo && baz not 1? Because true is 1.var foo = 1;var baz = 2;foo &&

    13小时前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信