Skip to content

JavaScript checks undefined or null or empty

  • by

Learn how to check for undefined, null, or empty strings in JavaScript. Use conditional statements and type-checking functions to determine whether a variable has a value or not. Improve your code’s reliability and prevent errors with these techniques.

JavaScript checks undefined or null or empty

Simple example code to check if a variable is undefined, null, or an empty string in JavaScript.

<!DOCTYPE html>
<html>
  <body>    
    <script>
        let variable;

        if (variable === undefined || variable === null || variable === '') {
            console.log('Variable is undefined, null, or empty');
        } else {
            console.log('Variable has a value');
        }

    </script>
  </body>
</html>

Output:

JavaScript checks undefined or null or empty

Alternatively, you can use a helper function to make the check more concise:

function isNullOrUndefinedOrEmpty(variable) {
  return variable === undefined || variable === null || variable === '';
}

let variable;

if (isNullOrUndefinedOrEmpty(variable)) {
  console.log('Variable is undefined, null, or empty');
} else {
  console.log('Variable has a value');
}

To check if a variable in JavaScript is undefined, null, or an empty string, and then display a message indicating which of these conditions it meets, you can use a combination of conditional statements and type-checking functions

let variable;

if (typeof variable === 'undefined') {
  console.log('Variable is undefined');
} else if (variable === null) {
  console.log('Variable is null');
} else if (variable.trim() === '') {
  console.log('Variable is empty');
} else {
  console.log('Variable has a value');
}

Alternatively, you can create a helper function to make the check it:

function checkVariable(variable) {
  if (typeof variable === 'undefined') {
    console.log('Variable is undefined');
  } else if (variable === null) {
    console.log('Variable is null');
  } else if (variable.trim() === '') {
    console.log('Variable is empty');
  } else {
    console.log('Variable has a value');
  }
}

let variable;

checkVariable(variable);

Comment if you have any doubts or suggestions for this JS variable type check example.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading