Ask coding questions

← Back to all posts
Can someone help me turn this into javascript?
MisledWater79 (0)

I don’t understand for loops in javascript and I was able to make something like what I want in python so can someone help translate it to javascript?

Answered by malvoliothegood (871) [earned 5 cycles]
View Answer
Comments
hotnewtop
malvoliothegood (871)
const mylist = ['1234567890','1234567890']
for (let i = 0; i < mylist.length; i++) {
  let numberString = mylist[i]
  for (let j = 0; j < numberString.length; j++) {   
    console.log(numberString[j])
  }
}
malvoliothegood (871)

@MisledWater79 You could also use one of the newish JS array methods called forEach and arrow functions, like so.

const numberStrings = ['1234', '5678']
numberStrings.forEach(string => string.forEach(char => console.log(char)))
InvisibleOne (2934)

For loops in javascript are a bit complicated, but once you understand them they get easier.
Basically, you can't do something for each item in a list, like you can in python.
Instead, you have to cycle through all the indexes of the items in a list.
A for loop in javascript looks like this:

for (variable; condition; do_something) {
}

At least that's the way I think about it.
The first thing you put in is a variable, and then the condition that it will loop through while that condition istrue, and then what you want to do to that variable.
So cycling through a list is:

for (var index=0; while_index_isn't_greater_than_list; add one to variable) {
}

Which is why this works

const myList = ['item1', 'item2', 'item3', 'item4', 'item5'];

for (var index; index < myList.length; index ++) {
  console.log(myList[index])
}

I'm not answer this question better then the person who already answered it, I just wanted to make sure you understood how and why the code works, so next time you'll be able to write for loops in javascript yourself.