JavaScript check if var is empty | Length and equality operator

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

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:

 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:

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:

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.