How to handle nulls and whitespaces in a single line – JavaScript

We can apply conditions to variables only if they have a proper value. While filling a form and leaving it blank, the system throws a validation error to handle the blank space string. We can handle these situations using various ways in JavaScript. Let’s have a look on the most simple way to handle nulls and whitespaces using just a single line in JavaScript.

Use of string functions like trim(), empty(), or length() checks if a string holds a proper value. A simple and easy way to check this without use of other functions is adding a "" to validate a string input.

Handling nulls and whitespaces in a single line

You can simply validate a string input inside an if condition, and use of quotation marks, and some operators, as shown in the code snippet below.

if((source_name != "") && (source_name != " ")){
    console.log("a valid source name is entered");
    // do something
}

The if condition above checks if the string is not empty and without any white space. It then corresponds to the process accordingly.

Similarly you can just change the operators to == instead of != and throw an error if string is empty or has any whitespace.

if((source_name == "") && (source_name == " ")){
    console.log("Error! Please enter a valid source name");
}

The straight forward method shown above allows us to validate for empty strings and white spaces, both in just a single line!

There are many other string methods in JavaScript, but I would always recommend use of the ones discussed above. Many JavaScript methods may not supported by some browsers. However, this simple code snippet can be easily implemented and supported by all browsers. Moreover, it covers two types of checks in a single line.

To handle nulls and whitespaces in JavaScript using string functions, refer to String functions to handle nulls and whitespaces.