Search code examples
javascriptarraysjsonscopejavascript-objects

Why am I getting "Can not read property 0 of undefined", when the object is very much there and I am trying to access it within scope?


I have a function like

(function next(index) {

  var someObject = { 0:{some:"one"}, 1:{thing:"none"}, 2:{seconds: 5} };

  setTimeout(function() {
    //code ...
  }, (someObject[0][seconds]*1000) );

)(0);

And I am getting the following error in the second last line

myscript.js:7 Uncaught TypeError: Cannot read property '0' of undefined

It seems to be a scope problem, because I tried to access the 0th key like someObject[0] as well as someObject.0 but no luck.

But according to my understanding, someObject is defined in the same scope as the call to setTimeout(). So why am I getting this error. How co I fix this?


Solution

  • When you access [seconds] using bracket notation, it attempts to evaluate the variable seconds and uses that result to determine the property to access. Specify it in string format ['seconds'] or use period notation as noted here:

    var someObject = { 0:{some:"one"}, 1:{thing:"none"}, 2:{seconds: 5} };
    
    
    try {
      console.log(someObject[2][seconds]*1000);
    } catch (e) {
      console.log(e.message);
    }
    console.log(someObject[2].seconds*1000);

    Additionally: someObject[0] is {some: "one"} which doesn't have any seconds parameter on it. I suspect you were trying to demonstrate someObject[2] instead.