How to check Javascript null
In this article, you will learn about how to check null in JavaScript.
JavaScript comes with a special type of value named null. In JavaScript, it is a primitive type value and represents an intentional absence of any Object value. Null is considered as a boolean type value and by default, it is treated as a falsy type boolean.
In JavaScript, a value is never set as null automatically. But in our programming journey, we need to set an Object value null explicitly for some reason. For example, you have a sayHello() function which creates an object with a name. Let’s see the object first in the below code:
function sayHello(name) {
return { message: `Hello, ${name}!` }
}
sayHello('Deven')
// Output: { message: 'Hello, Deven!' }
Now, let’s imagine for some reason we didn’t pass the arguments in the sayHello() function. In that situation, we can simply return null and it will understand that in sayHello() function an argument is missing.
function sayHello(name) {
if (!name) {
return null;
}
}
sayHello();
// Output : null
Here, returning JavaScript has a strict equality operator and by using it you can check for null. See the example:null indicates that the name parameter has no value and the sayHello()) object is not possible to create.
const noValueInObject = null;
const hasValueInObject = { name: 'Deven' };
console.log(noValueInObject === null)
console.log(hasValueInObject === null)
//output :
// true
// false
For the first case, the output for null is true and it is obvious because there is no value in the object and for the second case the output is for null is false because it has a value in the object.
Note: Null is only used for the object that has no value. If you set null for an object that contains an empty string you will get a typeError.