How to use if else In Javascript
In this approach, we will use the if-else method to solve the problem. we will check whether the value is null or not by passing the value into the if condition.
Note: When a variable is null, there is an absence of any object value in a variable. Null is often retrieved in a place where an object can be expected, but no object is relevant.
By the above condition, if my_var is null then the given if condition will not execute because null is a falsy value in JavaScript, but in JavaScript, there are many pre-defined falsy values like
- undefined
- null
- 0
- “” ( empty string)
- false
- NaN
So if my_var is equal to any of the above pre-defined falsy values then if the condition would not execute or vice-versa.
Example: This example shows the use of the above-explained approach.
let GFG_Var = "hello"
if (GFG_Var) {
console.log("It is not null");
}
else {
console.log("It is null");
}
Output
It is not null
How to check if a Variable Is Not Null in JavaScript ?
Our focus lies on understanding how to verify if a variable is not null in JavaScript. We’ll explore several methods to tackle this issue effectively.
These are the following ways to solve this problem:
Table of Content
- Using if else
- Using Lodash _.isNull() Method
- Using the typeof Operator:
Contact Us