Home > Mobile >  JS for loop types: why is one version output integer and another string?
JS for loop types: why is one version output integer and another string?

Time:12-24

I am doing an online course JavaScript. I am leraning right now the for loops and there are two types it is about: for (let i = 0; i < students.length; i ) for (let i in students) See the code. One is giving an output with student number 1-8 and the other gives an output like 01,11,21,31 aso. why?

"use strict"

const students= ["Melanie","Leni","Matilda","Niels","Anke","Juergen","Lilli","Hans"]

console.log("=========================================")
console.log("Variante 1\n")

for (let i = 0; i < students.length; i  ) {
  console.log(`Teilnehmer ${i 1} Name lautet: ${students[i]}`)
}

console.log("\n=========================================")
console.log("Variante 2\n")
for (let i in students) {
      console.log(`Teilnehmer ${i 1} Name lautet: ${students[i]}`)
}

I expected the code to deliver the same output. If i remove the 1 it is the same.

CodePudding user response:

Object property names are always strings. In the first version of your code, you are using a number in the loop, and JavaScript converts the number to a string when accessing the object property. Because it's a number, i 1 will be a numeric addition.

In the second version, your code uses the property names directly, so they're strings in the loop. Thus i 1 means string concatenation.

  • Related