3
Katakompe
46d

Okay I always found these js weirdnesses that you see in memes more or less logical if you think about it, but so far I could not find any logic behind this:

true&&undefined
>undefined

false&&undefined
>false

can anyone explain wtf they thought about there? undefined is falsy so why not just convert it to boolean implicitly!

Comments
  • 12
    True is truthy, and since this is an and operation we need to check every part of it. The last part to be checked is undefined

    False is falsy, and since it's an and operation we know it won't be true no matter what the following parts are, so we can just stop at false.
  • 4
    false&&undefined
    > Will return false as the first object is Falsey

    true&&undefined
    > undefined is Falsey and is returned as it's "false"

    One does not do javascript and expect it to make sense - that's just asking for trouble.
  • 4
    Damn you developers making sense of weird JS magic.

    But that's kind of logical if you don't forget basic principles of boolean evaluation.
  • 5
    As in C-like languages, && and || short-circuit: the second argument will only be evaluated if the first one is true (respectively, false).

    But like Perl and unlike C, they return the last value they had to evaluate, not true or false. Which is very handy in try-this-or-else-this-or-else-this type expressions.
  • 0
    everything in JS can be evaluated as boolean, So, if you use any variable in a conditional operation it will be evaluated as TRUE if it's defined and FALSE if it's undefined (unless they are actually boolean variables), So, In your case, undefined is same as false, hence, the output
Add Comment