Determining if a Variable Has Been Defined Using an Equality Operator in Javascript

The equality operator in JavaScript is used to compare two values and determine if they are equal. There are two main types of equality operators:

Strict Equality Operator (===):

    The strict equality operator compares both the value and the type of the operands.
    It returns true if both operands are equal in value and type, and false otherwise.


Abstract Equality Operator (==):

    The abstract equality operator compares the values after attempting to convert them to a common type.
    It returns true if both operands are equal in value after type coercion, and false otherwise.

Checking if a variable is defined

In this example, a variable myVariable is declared but not assigned a value. The if statement checks if myVariable is strictly equal (===) to undefined. Since it hasn't been assigned a value, it will be undefined, so the first branch of the if statement will be executed, logging "myVariable is undefined".

 
 
 let myVariable;
 if (myVariable === undefined) {
   console.log("myVariable is undefined");
 } else {
   console.log("myVariable is defined");
 }

Checking if an object property is defined

Here, myObject is an object with properties name and age. The hasOwnProperty method checks if the object has a property named "address". Since it doesn't, the second branch of the if statement will be executed, logging "Address is undefined".

 

 let myObject = { name: "John", age: 30 };
 if (myObject.hasOwnProperty("address")) {
   console.log("Address is defined");
 } else {
   console.log("Address is undefined");
 }
 
 
 

 

Checking if a function is defined

In this example, myFunction is defined as a function. The typeof operator is used to check the type of myFunction. If it's not equal to "undefined", it means the function is defined, and the first branch of the if statement will execut

 

 function myFunction() {
   console.log("Hello!");
 }

 if (typeof myFunction !== "undefined") {
   console.log("myFunction is defined");
 } else {
   console.log("myFunction is undefined");
 }

 
 

Checking if an array element is defined

myArray is an array with elements [1, 2, 3]. The code attempts to access the element at index 5. Since there is no element at index 5, myArray[5] will be undefined, and the second branch of the if statement will be executed.

 

 
 
 let myArray = [1, 2, 3];
 if (typeof myArray[5] !== "undefined") {
   console.log("Element at index 5 is defined");
 } else {
   console.log("Element at index 5 is undefined");
 }