Undeclared
- If any variable is not declared with the keywords like
var
,let
orconst
, then it is undeclared. That means the respective variable doesn’t exist in the program or has not been created yet. - If you will try to excess an undeclared variable, then it will through an error saying the following variable is
undefined
.
console.log(someVariable); // Uncaught ReferenceError: someVariable is not defined
Undefined
- If any variable is defined in the program but has not been assigned with any value, then it is undefined. That means the variable exists in the program but has no value assigned.
- If you will try to access an undefined variable, then it will return
undefined
.
let someVariable; console.log(someVariable); // undefined
Null
- If any variable is
null
, it means it is pointing to an object which has an empty value. The type ofnull
is an object. - If you will try to access the
null
variable, then it will returnnull
. - Both
undefined
andnull
values are treated as falsy for Boolean operations.
You can check the type of any variable using the keyword
typeof
.
let someVariable; console.log(typeof someVariable) // undefined someVariable = "some value"; console.log(typeof someVariable) // string someVariable = null; console.log(typeof someVariable) // object
Accessing the property of an undefined or null object
If any object is undefined
or null
and we are trying to access any property of that object, then it will through an error saying cannot read property of undefined
or null
.
let obj = {key: 123456}; obj = undefined; console.log(obj.key); // Uncaught TypeError: Cannot read property 'key' of undefined obj = null; console.log(obj.key); // Uncaught TypeError: Cannot read property 'key' of null
For better practice always check the type of any variable before accessing it to avoid unwanted run time errors.
let obj = {key: 123456}; obj = undefined; if (typeof obj !== undefined) { console.log(obj.key); }
Null check before accessing DOM element
const btn = document.getElementById('login'); if (btn !== null) { btn.click(); }
See next: How to check for null and undefined values.
Web Developer by Profession, Blogger by Passion.
JavaScript | React | Next | Angular | Vue | HTML | CSS