HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

What's the difference between undeclared, undefined and null in JavaScript?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
nulljavascriptwhatandbetweenundeclareddifferencetheundefined

Problem

A variable is undeclared if it has not been declared with an appropriate keyword (i.e. var, let or const). Accessing an undeclared variable will throw a ReferenceError.
A variable is undefined if it hasn't been assigned a value. undefined is a primitive data type in JavaScript and represents the absence of a value, intentional or otherwise.
A variable is assigned a value of null like any other value. null is also primitive data type in JavaScript and always represents the intentional absence of a value.
Undeclared variables will throw an error, which makes them easy to spot and are not very common anyways. undefined and null can be easily spotted with a conditional as they are both falsy values. Due to that, null and undefined are loosely equal (==), but not strictly equal (===).

Solution

console.log(x); // ReferenceError: x is not defined


A variable is assigned a value of null like any other value. null is also primitive data type in JavaScript and always represents the intentional absence of a value.
Undeclared variables will throw an error, which makes them easy to spot and are not very common anyways. undefined and null can be easily spotted with a conditional as they are both falsy values. Due to that, null and undefined are loosely equal (==), but not strictly equal (===).

Code Snippets

console.log(x); // ReferenceError: x is not defined
let x;
console.log(x); // undefined
let x = null;
console.log(x); // null

Context

From 30-seconds-of-code: undeclared-undefined-null

Revisions (0)

No revisions yet.