How can I determine if a variable is 'undefined' or 'null'?

JavaScript example to check whether if a variable is 'undefined' or 'null'.
Submitted by Pratishtha Saxena, on May 28, 2022

What are Undefined and Null Variables?

The variable that is not assigned any value is said to be undefined. It means that the variable is not defined by any value.

Null variable on the other hand is the variable that is defined but the value is not specified.

let a;
console.log(a); // undefined

let b = null;
console.log(b); // null

To determine whether the variable is null or undefined, == and === operators can be used. Both of them compares the variables but the difference is that Loose Equality Operator (==) treats null and undefined as the same and Strict Equality Operator (===) checks null and undefined separately.

Example 1:

let a;

if (a == null) {
	console.log('Null or undefined value');
} else {
	console.log(a);
}

Output:

Null or undefined value

Here, even the a is undefined but it will be treated the same as null because a loose equality operator has been used.

Example 2:

let a;

if (a === null) {
	console.log('Null Value');
} else if (a === undefined) {
	console.log('Undefined Value');
}

Output:

Undefined Value

Here, since a strict equality operator has been used, we will consider null and undefined values as two different cases. Therefore, to check whether the variable is undefined or null, a strict equality operator (===) should be used.

JavaScript Examples »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.