Skip to content

JavaScript check if var is empty | Length and equality operator

  • by

Use equality operator to check if var is empty in JavaScript. Also, value.length is also a good approach but should be used in the case of a string. If the value is a number, value.length will return 0

Examples of JavaScript check if var is empty

Let’s see the how to check it with examples:-

Using length and trim methods

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var name_first= "EyeHunts";

    if (name_first?.trim().length > 0) {
   		alert(name_first)
	}

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

Output:

 JavaScript check if var is empty

If just want to make sure, that code will run only for “reasonable” values, then you can, as others have stated already, write:

if (first_name) {
  // do something
}

 both null values, and empty strings, equals to false (i.e. null == false).

JavaScript check if a string is empty or whitespace

To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0, then you can be sure the original only contained whitespace. Try this:

var str = "    ";
if (!str.replace(/\s/g, '').length) {
  console.log('string only contains whitespace');
}

Q: How to check if a value is not null and not an empty string in JS?

Answer: If you want to confirm that a variable is not null and not an empty string specifically, you would write:

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var name_first= "EyeHunts";

    if(name_first !== null && name_first !== '') {
   		alert(name_first)
	}

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

Output:

value is not null and not empty string in JS

Do comment if you have any doubts and suggestions on this question.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
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