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,348
  • 4
  • 23
  • 40

2 Answers2

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,416
  • 3
  • 33
  • 43
  • so,which one is better to use and also fast - simple for or forEach? –  Jul 16 '17 at 21:11
-1

You shouldn't use for..in with arrays. Try for..of:

var first = document.querySelectorAll(".tab-menu ul li");
var f;
for(var el of first){
  f = el.innerHTML;
  console.log(f);
}
lilezek
  • 6,438
  • 1
  • 23
  • 44