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 (typeof something === "undefined") {
    alert("something is undefined");
}
click below button to copy the code. By JavaScript tutorial team

If an object variable which have some properties we can use same thing like this:

if (typeof my_obj.someproperties === "undefined"){
    console.log('the property is not available...'); // print into console
}
click below button to copy the code. By JavaScript tutorial team

Solution 2:

Correct Code

The most robust way to perform this test is:

if (typeof myVar === "undefined")
click below button to copy the code. By JavaScript tutorial team

This will always return the correct result, and even handles the situation where myVar is not declared.

Degenerate code. DO NOT USE.

var undefined = false;  // Shockingly, this is completely legal!
if (myVar === undefined) {
    alert("We have been misled. Run away!");
}
click below button to copy the code. By JavaScript tutorial team

Additionally, myVar === undefined will raise an error in the situation where myVar is undeclared.

Solution 3:

if ( typeof( something ) == "undefined") 
click below button to copy the code. By JavaScript tutorial team

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?

typeof x;                      // some string literal "string", "object", "undefined"
if (typeof x === "string") {   // === is redundant because we already know typeof returns a string literal
if (typeof x == "string") {    // sufficient
click below button to copy the code. By JavaScript tutorial team

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 (obj && obj.prop) {
  // Do something;
}
click below button to copy the code. By JavaScript tutorial team

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).


Related Searches to javascript tutorial - Undefined object property