This article will describe the equivalent of the isset() function of PHP in JavaScript.
JavaScript isset() Equivalent
Although there is not an isset() equivalent in JavaScript, there are numerous ways to check if a variable is possibly undeclared. Some of those approaches are given below:
Method 1: Using the “typeof” Operator
In JavaScript, the “typeof” operator is equivalent to “isset()”. It accepts an operand/variable and gives the type of its value. If the variable is not declared, it outputs the “undefined”.
Syntax
Use the following syntax for the typeof operator:
Example
Declare a variable “x” and assign it a value:
Call the typeof operator with the variable that tells the type of the value stored in a specified variable:
Output
Let’s see what would be done if the variable is not declared:
The output shows “undefined” because the variable “y” is not declared:
If the value is not declared or declared but is not assigned, then, use the below-given lines of code to verify it:
console.log("The x is the " + typeof x + " (" + x + ")");
}
else{
console.log("x is not defined");
}
The output shows the value and its type stored in the variable “x” because it is defined and not null:
Method 2: Using “hasOwnProperty()” Method
The “hasOwnProperty()” is equivalent to the isset() in JavaScript. It is used to determine whether a property is present inside an object. It returns “true” if the particular property is a direct property of the object or even though the value of the specified property is undefined.
Syntax
Follow the given syntax to verify the object’s property defined in the object:
Example
Create an object with its properties in a key-value pair:
name: 'Jenny',
age: 24
};
Check if “rollno” is the property of the object “info” or not:
It can be seen that the hasOwnProperty returns “false” which means the specified property does not exist in the object:
Method 3: Using the “in” Operator
In JavaScript, you can use the “in” operator as an equivalent to the isset() in PHP. It determines if a property is present inside an object or the prototype chain of that object.
Syntax
The following syntax is utilized for using the “in” operator:
Example
Check the property “age” in object “info” using the “in” operator:
Output
That was all about the equivalent of isset() in JavaScript.
Conclusion
There is no built-in “isset()” function in JavaScript, but there are numerous ways to check if a variable is possibly undeclared, such as the “typeof” operator, “hasOwnProperty()” method, and the “in” operator. This blog discussed the equivalent of isset() in JavaScript with the help of practical examples.