javascript tutorial - [Solved-5 Solutions] Undefined object property - javascript - java script - javascript array
Problem:
What's the best way of checking if an object property in JavaScript is undefined?
Solution 1:
Use:
If an object variable which have some properties we can use same thing like this:
Solution 2:
Correct Code
The most robust way to perform this test is:
This will always return the correct result, and even handles the situation where myVar is not declared.
Degenerate code. DO NOT USE.
Additionally, myVar === undefined will raise an error in the situation where myVar is undeclared.
Solution 3:
Solution 4:
I'm not sure where the origin of using ===
with typeof
came from, and as a convention WE see it used in many libraries, but the typeof operator returns a string literal, and we know that up front, so why would we also want to type check it too?
Solution 5:
We didn't see (hope We didn't miss it) anyone checking the object before the property. So, this is the shortest and most effective (though not necessarily the most clear):
If the obj or obj.prop is undefined, null, or "falsy", the if statement will not execute the code block. This is usually the desired behavior in most code block statements (in JavaScript).