Why work for and forEach different?

Explain why the forEach works, and for no. This accordion. Here is a working version with forEach:

(accordeon function() {
 var el = document.querySelectorAll('.faq-accordeon-item__question');
 for(var i = 0; i < el.length; i++) {
 el[i].addEventListener('click', function(e) {
 var show = document.querySelectorAll('.faq-accordeon-item__info');

 show.forEach(function(item) {
 item.style.display = 'none';
console.log(32);
});

 e.target.nextElementSibling.style.display = 'block';
});
}
})();

But non-working for:
(accordeon function() {
 var el = document.querySelectorAll('.faq-accordeon-item__question');
 for(var i = 0; i < el.length; i++) {
 el[i].addEventListener('click', function(e) {
 var show = document.querySelectorAll('.faq-accordeon-item__info');

 for(var i = 0; i < show.lenght; i++) {
 show[i].style.display = 'none';
console.log(32);
}

 e.target.nextElementSibling.style.display = 'block';
});
}
})();

Of course, I can write forEach, but I wonder what is the difference between them in this context.
June 27th 19 at 15:29
2 answers
June 27th 19 at 15:31
Solution
show.lenght — a typo here (instead of length).
Thanks, the console is somehow silent about the typo) - lia.Larson47 commented on June 27th 19 at 15:34
: well, when you read an unknown property, just get undefined. From the point of view of JS i < undefined is quite a legitimate operation, to not swear on that:)

By the way, for most likely faster than forEach. And it seems not all browsers have the result of querySelectorAll is property of forEach. - genevieve_Upton commented on June 27th 19 at 15:37
June 27th 19 at 15:33
To use it for.
QuerySelectorAll method returns not an array, but an object of type NodeList, in which the forEach method was added quite recently.
https://developer.mozilla.org/en-US/docs/Web/API/N...
That is, it will work only in most fresh browsers (probably tested in latest Chrome).
Well either you have had polyfil add.
well, in this case, it is easier still in the array to scaliti. Using Array.prototype.slice for example. - lia.Larson47 commented on June 27th 19 at 15:36
Can popular practice, but the special do not see sense.
Saving characters was not obtained, and the resources still eats.
I do so only in cases where this array is then supposed to be used repeatedly. - genevieve_Upton commented on June 27th 19 at 15:39
That's right, in Safari do not work forEach. Yes, and the speed for above. - willow.Hand commented on June 27th 19 at 15:42
+ two cycles using variable i
change the name of the variable - Evie commented on June 27th 19 at 15:45
: Okay, thank you. - lia.Larson47 commented on June 27th 19 at 15:48

Find more questions by tags JavaScript