hi i am preparing for js interview. i saw this question.
if var a=2, var b =3
What would be the value of a&&b
?
The answer given is 3.
I am not able to understand why is this the answer. Can you help.. Thanks.
hi i am preparing for js interview. i saw this question.
if var a=2, var b =3
What would be the value of a&&b
?
The answer given is 3.
I am not able to understand why is this the answer. Can you help.. Thanks.
The binary operators do NOT behave like other c based languages. See more about truthy and falsey values here
&&
is defined as follows.
If the first operand is truthy then the result is the second operand. Otherwise it is the first.
false && true // false the first operand is falsey
0 && true // 0. 0 is a falsy value so the first value is used
1 && 0 // 0. The first value is truthy
// so the second value is used
'hello' && 'world' // 'world' the first value is truthy
// so yield the second value.
||
is defined as follows.
If the first operand is truthy then the result is the first operand. Otherwise it is the second.
false || true // true, first value is falsey so yield second
0 || true // true, first value is falsey so yield second
1 || 0 // 1, first value is truthy use it.
'hello' || 'world' // 'hello', first value is truthy so yield it.
&&
and ||
are "Short-circuit"This means that there are ways to structure code such that not all expressions are evaluated. This can be convienient at times but is double edged.
function launchNukes() { /* TODO */ }
0 && launchNukes(); // nukes do not fire
1 && launchNukes(); // nukes fire
0 || launchNukes(); // nukes fire
1 || launchNukes(); // nukes do not fire
&& is an AND operator, just like most everywhere else. Most languages, JavaScript included, will stop evaluating an AND operator if the first operand is false.
You can read it like that:
a
is true , return value will be b
a
is false , return value will be a
So && return values of operands not false
and true
.
for your example,
2 && 3 // return 3 because 2 is true