Undeclared, undefined and null in Javascript
James L
Posted on August 6, 2022
What is an undeclared variable?
- An undeclared variable is created when you assign a value to an identifier which has not been previously created using
var
,let
orconst
. - Are defined globally outside of the current scope.
- Can only occur outside of strict mode. If enabled, strict mode will throw a
ReferenceError
instead.
// undeclared variable
// assigned global scope
x = 1;
console.log(x) // 1
'use strict'
// Throws ReferenceError: x is not defined
x = 1;
What is an undefined variable?
- An
undefined
variable in Javascript is a variable which has been declared but has no value assigned to it. - It has the type
undefined
.
var x;
console.log(x) // undefined
What is the difference between null and undefined?
-
undefined
is the value of a variable which has not been assigned a value. -
null
has to be assigned to a variable. -
null
has the typeObject
var x; // x is undefined
var y = null; // y is null
console.log(x == y); // true
console.log(x === y); // false
- Using the abstract equality operator
==
,null
andundefined
will be equal. - Using the strict equality operator,
===
,null
andundefined
are not equal as x is of typeundefined
and y is of typeObject
.
💖 💪 🙅 🚩
James L
Posted on August 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.