Tuesday, May 29, 2012

Detecting an undefined object property in JavaScript


What's the best way of checking if an object property in JavaScript is undefined?



Sorry, I initially said variable rather than object property. I believe the same == undefined approach doesn't work there.


Source: Tips4all

16 comments:

  1. Use:

    if (typeof something === "undefined")
    alert("something is undefined");

    ReplyDelete
  2. I believe there are a number of incorrect answers to this topic.
    Contrary to common belief "undefined" is NOT a keyword in javascript, and can in fact have a value assigned to it.

    // Degenerate code. DO NOT USE.
    var undefined = false; // Shockingly, this is completely legal!
    if(myVar === undefined) {
    alert("You have been mislead. Run away!");
    }


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

    The most robust way to perform this test is:

    if(typeof myVar === "undefined")


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

    ReplyDelete
  3. In JavaScript there is null and there is undefined. They have different meanings.


    undefined means that the variable value has not been defined; it is not known what the value is.
    null means that the variable value is defined and set to null (has no value).


    Marijn Haverbeke states, in his free, online book "Eloquent JavaScript" (emphasis mine):


    There is also a similar value, null, whose meaning is 'this value is defined, but it does not have a value'. The difference in meaning between undefined and null is mostly academic, and usually not very interesting. In practical programs, it is often necessary to check whether something 'has a value'. In these cases, the expression something == undefined may be used, because, even though they are not exactly the same value, null == undefined will produce true.


    So, I guess the best way to check if something was undefined would be:

    if (something == undefined)


    Hope this helps!

    Edit: In response to your edit, object properties should work the same way.

    var person = {
    name: "John",
    age: 28,
    sex: "male"
    };

    alert(person.name); // "John"
    alert(person.fakeVariable); // undefined

    ReplyDelete
  4. if ( typeof( something ) == "undefined")


    This worked for me while the others didn't.

    ReplyDelete
  5. I'm not sure where the origin of using === with typeof came from, and as a convention I see it used in many libraries, but the typeof operator returns a string literal, and we know that up front, so why would you 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

    ReplyDelete
  6. It's better to use the strict equality operator:

    if (variable === undefined) {
    alert('not defined');
    }


    x == undefined also checks whether x is null, while strict equality does not (if that matters).(source)

    Or you can simply do this:

    if (!variable) {
    alert('not defined');
    }


    Here you check if there's any value that can make the variable look false (undefined, null, 0, false, ...). Not a good method for integers ('0' is not false), but might do well for object properties.

    ReplyDelete
  7. Though that I'd throw in that its sometimes worth asking if checking for undefined is really what you want to do:

    I've just been refactoring a bunch of code that was using this kind of construct (incorrectly).

    There was a bunch of checks whether an object had a given property.

    if( typeof blob.x != 'undefined' ) { fn(blob.x); }


    Which can be more clearly written without a check for undefined.

    if( "x" in blob ) { fn(blob.x); }

    ReplyDelete
  8. The solution is incorrect. In javascript,

    null == undefined


    will return true because they both are "casted" to a boolean and are false. The correct way would be to check

    if (something === undefined)


    which is the identity operator...

    ReplyDelete
  9. if you do:

    if(myvar == undefined )
    { alert('var does not exists or is not initialized'); }


    It will fail when the var myvar does not exists because myvar is not defined, so the script is broken and the test has no effect.

    Because the window object has a global scope (default object) outside a function, a declaration will be 'attached' to the window object.

    for example:

    var myvar = 'test';


    the global var myvar is the same as window.myvar or window['myvar']

    To avoid errors to test when a global variable exists, you better use:

    if(window.myvar == undefined )
    { alert('var does not exists or is not initialized'); }


    The question if a var really exists doesn't matter, it's value is incorrect, that is the only thing that counts. Otherwise, it is silly to initialize variables with undefined, better use the value false to initialize. When you know that all variables that you declare are initialized with false, you can simply check it's type or rely on !window.myvar to check if it has a proper/valid value. So even when the variable is not defined then !window.myvar is the same for myvar=undefined or myvar=false or myvar=0.

    When you expect a specific type, test the type of the variable. To speed up testing a condition you better do:

    if( !window.myvar || typeof window.myvar != 'string' )
    { alert('var does not exists or is not type of string'); }


    When the first and simple condition is true, the interpreter skips next tests.

    It is always better to use the instance/object of the variable to check if it got a valid value. It is more stable, a better way of programming.

    Cheers!

    Kind regards,
    Erwin Haantjes

    ReplyDelete
  10. function isUnset(inp) {
    return (typeof inp === 'undefined')
    }


    Returns false if variable is set, and true if is undefined.

    Then use:

    if (isUnset(var)) {
    // initialize variable here
    }

    ReplyDelete
  11. You can get array all undefined with path using following code.

    function getAllUndefined(object) {

    function convertPath(arr, key) {
    var path = "";
    for (var i = 1; i < arr.length; i++) {

    path += arr[i] + "->";
    }
    path += key;
    return path;
    }


    var stack = [];
    var saveUndefined= [];
    function getUndefiend(obj, key) {

    var t = typeof obj;
    switch (t) {
    case "object":
    if (t === null) {
    return false;
    }
    break;
    case "string":
    case "number":
    case "boolean":
    case "null":
    return false;
    default:
    return true;
    }
    stack.push(key);
    for (k in obj) {
    if (obj.hasOwnProperty(k)) {
    v = getUndefiend(obj[k], k);
    if (v) {
    saveUndefined.push(convertPath(stack, k));
    }
    }
    }
    stack.pop();

    }

    getUndefiend({
    "": object
    }, "");
    return saveUndefined;
    }


    jsFiddle link

    ReplyDelete
  12. Object.hasOwnProperty(o, 'propertyname');

    This doesn't look up through the prototype chain, however.

    ReplyDelete
  13. These threw exceptions for me The following code will work for variables which are not created inside a function

    var mygroup=null;

    function isdefined( variable)
    {
    return (typeof(window[variable]) == "undefined")? false: true;
    }
    window.onload=function()
    {
    alert(isdefined('mygroup'));
    }


    But However using try and catch was the only solution which returned zero exceptions at all places.

    ReplyDelete
  14. Please try the following example it works for me and it is as per w3schools standard

    var t1;
    if (t1 == undefined) {
    alert('not defined');
    }

    ReplyDelete
  15. if (somevariable == undefined) {
    alert('the variable is not defined!');
    }


    You can also make it into a function, as shown here:

    function isset(varname){
    return(typeof(window[varname]) != 'undefined');
    }

    ReplyDelete
  16. I've tested with undefined but is not recognized on object as standard command (i probably wrong same case sensitive), as said Ricky undefined = null. I've tested with null and finally work:

    document.getElementById("objectname") === null


    I've used it to check(uncheck) unknown number of checkboxes without test all objects in the page.

    ReplyDelete