Can I verify if a JavaScript variable is loaded if so, how?

JavascriptWeb DevelopmentObject Oriented Programming

To verify if a JavaScript variable has been loaded or not, we can check if it is undefined or has a null value by doing comparison for both the values. We can also use typeof() since it returns string always to know if variable has been loaded or not.

Following is the code to verify if a JavaScript variable has been loaded or not −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Check if a variable is loaded or not</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to see if the object obj has been loaded or not
</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let obj;
   BtnEle.addEventListener("click", () => {
      if (obj === null || obj === undefined) {
         resEle.innerHTML = "The object obj hasn't loaded yet";
         obj = { firstName: "Rohan", lastName: "Sharma" };
      }
      else {
         resEle.innerHTML = "The object obj has been loaded";
      }
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

On clicking the ‘CLICK HERE’ button again −

raja
Published on 18-Jul-2020 10:50:08
Advertisements