2

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.

1 Answers1

1

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    Wow ok, thank to you @pointy. Thats not easy to understand as a newbie. :-D But it is important to understand the differnce and I am thankful for your explanation. I wish you a merry christmas and a happy new year! – Niels von Daake Dec 23 '22 at 13:59
  • 1
    @NielsvonDaake It's important to be aware that Arrays are also objects, and when enumerated, the keys come out as `"0"`, `"1"`, `"2"` etc... (i.e. strings). – spender Dec 23 '22 at 14:00
  • @Spender yes, thank you. The array numbers I understand. That an array always begin at 0 instead of 1 Thats why I wantes to manipulate the number given so it starts with 1 instead of 0 in the listing. :-) – Niels von Daake Dec 23 '22 at 14:02
  • I now addes the parseInt : console.log(`Teilnehmer ${parseInt(i)+1} Name lautet: ${students[i]}`) Like this it works. But is there another solution? – Niels von Daake Dec 23 '22 at 14:08
  • 1
    https://stackoverflow.com/questions/1133770/how-to-convert-a-string-to-an-integer-in-javascript – epascarello Dec 23 '22 at 14:11
  • 1
    @NielsvonDaake you could use `${+i + 1}` – Pointy Dec 23 '22 at 14:20
  • @epascarello Thanks. That was also helpful. I tried it out now with: console.log(`Teilnehmer ${i*1+1} Name lautet: ${students[i]}`) and it work too. Great, what a lesson today! Thanks to you all! and a Merry Christmas! – Niels von Daake Dec 23 '22 at 14:20
  • omg one more solution. What a great day for me :-) – Niels von Daake Dec 23 '22 at 14:22