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?

Comments
hotnewtop
[deleted]
[deleted]

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

InvisibleOne (3264)

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:

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:

Which is why this works

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.