Why 'banana'&&'apple' outputs apple? | SoloLearn: Learn to code for FREE!

0

Why 'banana'&&'apple' outputs apple?

I came across this code in the JS Quiz and couldn't understand the logic behind it. https://code.sololearn.com/W1DFG8fQ2Kf3/?ref=app

1/20/2021 4:49:45 PM

silentlearner

3 Answers

New Answer

+2

Hi, 'banana' is truthy value, it can be converted to true in a Boolean context. 'banana' and 'apple' can be converted to True, so it returns 'apple' There is a good doc here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

+2

The && operator returns true only if the expression on both sides evaluates to true. So first it checks 'banana' which is true and then 'apple' which is also true. But you get 'banana' as result because it returns the last expression which evaluated to true. You can replace the && with || and you can see that it prints 'banana' because for || operator to return true, expression on any one side must return true. Since 'banana' returns true, it doesn't even care to check for the other expression which is 'apple'.

+1