How to Check If an Object Property Exists in JavaScript
Checking an object property for "null" or "undefined" is an error-detection procedure performed in JavaScript to avoid bugs in your website code. If you attempt to use an object set to "null," JavaScript returns an error in the reader's Web browser, and it causes the page to function improperly for your users. An undefined JavaScript object means the object is created, but it is not assigned to an element located on your Web page.
Instructions
-
-
1
Right-click the HTML page that contains your JavaScript code. Select "Open With" to view a list of compatible programs. Choose "Notepad" if you do not have a third-party JavaScript editor.
-
2
Press "Ctrl" and "F" to open the "Find" dialog window. Type "<script" and press "Enter" to scroll down to the section of your HTML code that contains the JavaScript text.
-
-
3
Type the "if" statement that checks the object's value. You must check for "null" and "undefined" to verify that the object has an assigned element. The following code shows you how to verify an object named "myvar":
if(typeof(myvar) !== 'undefined' && var != null) {
alert("Object is defined");
}
The code above only prints "Object is defined" to the user's screen if the object is defined and exists.
-
4
Press "Ctrl" and "S" to save the changes. You can verify the new JavaScript code by double-clicking the file and opening it with your web browser.
-
1