Search code examples
javascriptcrashvariable-length

using .length on vars that don't have the length property results in crash


I have a big array which contains all kind of types (booleans, arrays, null, ...), and I am trying to access their propiety arr[i].length, but some of them obiously fail to have length.

I wouldn't mind if the guys missing length returned undefined (I could simply use arr[i].length||0 or something like that), but this is not the case, the whole thing crashes with some values (null or undefined for example).

var i, len, arr;

arr = [true, ["elm_0"], 99, "abc"]; //crashes if you add 'null' or 'undefined'

for(i = 0, len = arr.length ; i<len ; i++){
    document.write(arr[i].length + "<br>");
}

document.write("I was executed");
  • What other vars will crash besides null and undefined?
  • How to prevent this from happening?

Solution

  • Check for arr[i] before arr[i].length

    var i, len, arr;
    
    arr = [true, ["elm_0"], 99, "abc"];
    
    if(arr) for(i = 0, len = arr.length || 0 ; i<len ; i++){
        if(arr[i]) document.write((arr[i].length || 0) + "<br>");
        else document.write(0 + "<br>"); // what to do if no arr[i]
    }
    
    document.write("I was executed");
    

    You can use a ternary operator, too (arr[i]?arr[i].length||0:0)