Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does an undefined operand not return false?

Given the following:

let a;
let b = false;
let c = a && b === undefined;

In my understanding, undefined is a falsy value, so why is it that c has value undefined instead of false?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Given your example, a is undefined. Therefore, a && ... is undefined && ..., and since undefined is falsy, the left hand side short circuits. That means, it never evaluates the right hand side.

If the left hand side is falsy, there’s nothing the right-hand side of an && can do to change that. To use an analogy, false && anything always evaluates to false, and in JavaScript, it stops there and ignores anything.

Now, the question may be, "Why doesn’t it return false instead of undefined?" MDN says:

The logical AND operator, &&

If the first object is falsy, it returns that object

false && "dog" // ↪ false

0 && "dog" // ↪ 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading