0

There is one interview question below. The logical AND of two truths should be true. But the output is 3. Why?

var a = 2;
var b = 3;

var c = a && b; // value of c = 3

console.log(c);
BILAL AHMAD
  • 686
  • 6
  • 14
  • `a` is truthy, so it evaluates to the second operand. – Alex Jan 25 '18 at 19:06
  • Because JavaScript `&&` and `||` don't work the same way they do in languages like C and Java. They use fall-through/short circuit logic. – JLRishe Jan 25 '18 at 19:08
  • 2
    You shouldn't assume the operators such as `&&` in any programming language have anything to do with "logical AND". You should find out what they are defined to do. – NetMage Jan 25 '18 at 19:10

2 Answers2

1

Check this out.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

If you use && with non-boolean values, it returns the first element if it can be converted to false. If it cannot converted to false, it returns second element

arunmmanoharan
  • 2,535
  • 2
  • 29
  • 60
0

Returns a if it can be converted to false; otherwise, returns b.