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

20th Jan 2021, 4:49 PM
silentlearner
silentlearner - avatar
3 Respuestas
+ 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
20th Jan 2021, 5:13 PM
Anaïs V.
Anaïs V. - avatar
+ 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'.
20th Jan 2021, 5:30 PM
Avinesh
Avinesh - avatar
+ 1
Yes
22nd Jan 2021, 10:25 AM
Ramna Ramna
Ramna Ramna - avatar