0

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.

2
  • Here i becomes a global variable use let,var here for(i = 0; i <= all_videos.length; i++) { Commented May 5, 2020 at 16:38
  • Is there anything in all_videos in that console.log call ? Commented May 5, 2020 at 16:39

2 Answers 2

2

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'));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just removing the the = from <= resolved the error. :) Are there any cases where keeping i global would have become a problem?
@RealNoob Global variable creates risk in javascript since it can be accessed by other function. For example if in other loop if you use same i then there will be a collision . So scoping variable is important
1

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++) {

Comments

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.