DEV Community

Nashmeyah
Nashmeyah

Posted on

Undefined vs. Null vs. Undeclared

A typical JavaScript interview question asks "What is the difference between a variable that is: null, undefined and undeclared?"

Lets break each one down and understand what each one means and how it relates to programming.

Null:

"The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations." (MDN Web Docs, Online). Null means that the value is absent, not 0... the value points to no object.

x = null;
Enter fullscreen mode Exit fullscreen mode

Undefined:

"The undefined property indicates that a variable has not been assigned a value, or not declared at all.", (W3Schools, Online).

let x
console.log(x + "test")
// x is undefined
Enter fullscreen mode Exit fullscreen mode

Undeclared:

Variables that have been declared without using const, var, or let. For Example:

testVar = "This is undeclared"
// as opposed to
let testVar = "This is declared"
Enter fullscreen mode Exit fullscreen mode

Now lets discuss the differences between all three. Null is pointing to nothing in memory. Undefined is a variable that has not been assigned any value. Lastly, undeclared is a variable that has not been properly declared using const, var, or let.

Discussion (0)