Real Noob
Real Noob

Reputation: 1591

Getting variable is indefined error inside a for loop

Here is my JavaScript code:

var all_videos = document.querySelectorAll(".video-feed-item-wrapper");
var all_urls = [];
console.log(all_videos.length);
for(i = 0; i <= all_videos.length; i++) {
  all_urls.push(all_videos[i].getAttribute('href'));
}
console.log(all_urls);

It gives me the error all_videos[i] is undefined. Why is it undefined?

Thanks.

Upvotes: 0

Views: 37

Answers (2)

brk
brk

Reputation: 50346

Two issues here , first i becomes a global variable and instead i <= all_videos.length use only i < all_videos.length. It is undefined because i trying the access the element which is not available. The element is not available because index starts from 0

for(i = 0; i < all_videos.length; i++) {
  all_urls.push(all_videos[i].getAttribute('href'));
}

Upvotes: 2

Michał Z.
Michał Z.

Reputation: 1392

For loop should iterate from 0 to length-1

Condition in for loop should be i < all_videos.length instead of i <= all_videos.length

The correct line should be:

for(i = 0; i < all_videos.length; i++) {

Upvotes: 1

Related Questions