Is there is a standard function to check for null, undefined, or blank variables in JavaScript?

JavascriptObject Oriented ProgrammingProgramming

No there is not a standard function to check for null, undefined or blank values in JavaScript. However, there is the concept of truthy and falsy values in JavaScript.

Values that coerce to true in conditional statements are called truth values. Those that resolve to false are called falsy.

According to ES specification, the following values will evaluate to false in a conditional context −

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

This means that none of the following if statements will get executed −

if (null) 
if (undefined) 
if (NaN) 
if ("") 
if (0) 
if (false)

Keywords to verify falsys

But there are some existing Keywords to check whether a variable is null, undefined or blank. They are null and undefined.

Example

Following example verifies for null, undefined and, blank values −

<!DOCTYPE html> <html> <head> <title>To check for null, undefined, or blank variables in JavaScript</title> </head> <body style="text-align: center;"> <p id="output"></p> <script> function checkType(x) { if (x == null) { document.getElementById('output').innerHTML += x+'The variable is null or undefined' + '<br/>'; } else if (x == undefined) { document.getElementById('output').innerHTML += 'The variable is null or undefined' + '<br/>'; } else if (x == "") { document.getElementById('output').innerHTML += 'The variable is blank' + '<br/>'; } else { document.getElementById('output').innerHTML += 'The variable is other than null, undefined and blank' + '<br/>'; } } var x; checkType(null); checkType(undefined); checkType(x); checkType(""); checkType("Hi"); </script> </body> </html>
raja
Updated on 26-Aug-2022 11:54:34

Advertisements