0

I wounder why can't I access array item by index? I've created global array just like this:

var myArr=[];

Then in a function I've used a simple loop to fill it with numbers from 1 to 10 just in test purposes. It seems it is filled because if I call

console.log(myArr);

It returns me this enter image description here

But if I try to use indexes in the same console call

console.log(myArr[2]);

It returns undefined and also myArr.length returns 0

Why??

4
  • Share all your index code and where is it called Commented Nov 9, 2020 at 12:24
  • I would imagine you have a shadowing or scoping issue, but probably need to see a bit more code that shows what happens between declaration and access to determine for sure. Definitely double check the rules for scope in JavaScript. Commented Nov 9, 2020 at 12:25
  • try your code in console, its workin good. You must give more information or create minimal demo with snippet. var arr = [0,1,2,3,4,5,6,7,8]; console.log(arr[1]); console.log(arr.length); Commented Nov 9, 2020 at 12:27
  • 1
    browser consoles usually log a live reference of the object (in this case your array). Your array is most likely being populated asynchronously, meaning that when you try and access your data there is nothing inside of it, but when you look at the console at a letter point in time, it will contain your data. To print a "snapshot" of your array (rather than a reference), try doing console.log(JSON.stringify(myArr)), that will show you what it is at the time that its being logged Commented Nov 9, 2020 at 12:28

1 Answer 1

1

When you click on the array in your developer tools, it shows you the current values inside the array. I assume you are inserting items into the array after calling console.log on the array.

Since you expand the array in the developer tools after it has been populated, it appears populated, but at the time of console.logging, it actually isnt (and is just an empty array).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Yes the problem was exactly in unpopulated array. 1 sec delay resolved my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.