
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Verify if a JavaScript Variable is Loaded
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
<!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 −
Advertisements