2

I am having trouble understanding how this for-in loop showing Undefined values at the end in JavaScript, but in loop the length of first is 3. So, why so many undefined values.

<div class="tab-menu">
    <ul>
        <li id="first">first item</li>
        <li id="second">second item</li>
        <li id="third">third item</li>
    </ul>
</div>

and the loop -

var first = document.querySelectorAll(".tab-menu ul li");
var f;
for (var i in first) {
    f = first[i].innerHTML;
    console.log(f);
}

It'll give this in console -

"first item"
"second item"
"third item"
undefined
undefined
undefined
undefined
undefined
undefined
Talha Awan
  • 4,573
  • 4
  • 25
  • 40

1 Answers1

2

You could use forEach.

var first = document.querySelectorAll(".tab-menu ul li")

first.forEach(function(e) {
  var f = e.innerHTML
  console.log(f)
})
Ikbel
  • 7,721
  • 3
  • 34
  • 45
  • so,which one is better to use and also fast - simple for or forEach? –  Jul 16 '17 at 21:11