Home > Enterprise >  Why does an undefined operand not return false?
Why does an undefined operand not return false?

Time:05-23

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?

CodePudding user response:

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

CodePudding user response:

c ends up undefined because a is undefined. The && operator stops with the first value that's falsy through a process called short circuiting

CodePudding user response:

First, all declarations with var and let are moved to the top (Hoisting) and are assigned undefined (const isn't assigned anything).

let a;
let b;
let c;

So by doing c = a you're assigning undefined to c once again.

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

To me, undefined is not a falsy value, you cannot do operations on it:

undefined===false
false

undefined && true
undefined

undefined && false
undefined
  • Related