Undefined array element becomes defined and null

Discussion in 'Javascript' started by Tim Streater, Dec 18, 2011.

  1. Tim Streater

    Tim Streater Guest

    I have a JavaScript array, myArray. I happen to know that let's say
    element 27 is undefined - it's never been created. It appears that I can
    detect this with:

    if (myArray[27]==null)
    alert (myArray[27]);

    The alert puts up 'undefined'. Is it valid to be able to detect the
    undefined stater of element 27 in this way?

    Initially I thought perhaps that the act of accessing the element
    created it and set it to null, but apparently not if the alert is
    anything to go by. Or is this just a quirk of Safari?
    Tim Streater, Dec 18, 2011
    1. Advertisements

  2. Tim Streater

    J.R. Guest

    In this particular case, we should use the strict Equals Operator (===)
    than just the Equals Operator (==), because undefined == null, for
    instance, produces true, whereas undefined === null yields false.

    Note: Douglas Crockford's advice is to never use [what he calls] the
    evil twins (== and !=). Instead, we should always use === and !==,
    although Crockford's advice is a tad exaggerated when dealing with the
    typeof operator which always returns a string value.

    Another important thing: if we access a missing array element, we will
    get the undefined value, not null. So, the OP's code might be rewritten to:

    var missingElem = myArray[27];
    if (typeof missingElem == 'undefined') {
    alert('this is a missing element in myArray');
    J.R., Dec 19, 2011
    1. Advertisements

  3. Tim Streater

    Tim Streater Guest

    So no magic then - good!

    Joao and Stefan - thanks both for a clear summary.
    Tim Streater, Dec 19, 2011
  4. Tim Streater

    Evertjan. Guest

    Thomas 'PointedEars' Lahn wrote on 19 dec 2011 in comp.lang.javascript:
    What is the sense in making THE global object undefined,
    except to render the script useless?

    What would happen to your


    Evertjan., Dec 19, 2011
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.