1

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.

Marc Andre Jiacarrini
  • 1,424
  • 1
  • 19
  • 36

2 Answers2

2

&& and || do not create true or false. They return one of the operands.

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.

Examples

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.

Examples

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
Community
  • 1
  • 1
t3dodson
  • 3,484
  • 2
  • 27
  • 36
1

&& 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:

  • if a is true , return value will be b
  • if 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
bigOther
  • 9,792
  • 5
  • 45
  • 87