JavaScript

How to Check for Null in JavaScript

In JavaScript null parameter is used to declare a variable without assigning a value. On a Web page, these simple null variables are used for declaring objects that can be defined afterwards. JavaScript also offers null as an initial type that contains a “null” value. Also, If the expected object is not created then a function or a variable will return null.

Null values cause problems in the calculation or the manipulation of an object. However, If you declare variables in your code and check for null values before execution, then there exists less chance of encountering errors.

In this post we will learn about how to check for null in JavaScript with the help of a suitable example. So, let’s start!

How to check for null in JavaScript

Now we will implement an example in JavaScript to check out the null value. For this purpose, we will define a function named “info()” that checks the passed argument “arg” for the null value with the help of the “if” statement:

function info(arg) {
      if(arg == null) {
          console.log('Passed argument is null');
      }
      else {
          console.log ('Passed argument is not null');
      }
}

In case, if the value of the passed argument “arg” is null, “if” statement will execute and display the specified message “Passed argument is null”, otherwise the control will move towards the “else” statement.

We will now invoke the “info()” function three times while passing the values: “linuxhint”, “94”, and “null”:

info('linuxhint');
info(94);
info(null);

As the passed first two values are not of null type, the message added in the “else” block of the “info()” function will be displayed on the console window. Whereas, when “null” is passed as “arg”, you will see a message stating that “Passed argument is null”:

The above-given output signifies that our created “info()” function is successfully checking for the null values.

Conclusion

In JavaScript, the condition “arg == null” can be used to check passed arguments for null values. In your program, you can create a function named “info()” that accepts any values as an argument. Then add an “if” statement and specify “arg == null” as its condition. The added condition will be executed if the passed value is null otherwise, the execution control will move towards the “else” statement. This post discussed the method to check for null in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.