Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could you explain these two javascript examples?

Tags:

javascript

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);
like image 346
runeveryday Avatar asked Jun 24 '11 11:06

runeveryday


2 Answers

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.

like image 159
Frédéric Hamidi Avatar answered Nov 07 '22 05:11

Frédéric Hamidi


&& 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
like image 45
meo Avatar answered Nov 07 '22 04:11

meo