+ 4
Understanding JavaScript Loops
I'm having a hard time, understanding JavaScript loops. I've read the lessons about loops. However, at this point, all I'm doing is memorising the code from the lesson without understanding the concept. Can anyone share an example of a practical use of loops(or even better, maybe from a code you have)? I apologize if it's a stupid question. Thank you, in advance.
4 Respuestas
+ 8
//Loops are used when we want to run the same code over and over again, each time with a different value.
var users= ["user1", "user2", "user3", "user4", "user5"];
var text = "";
var i;
for (i = 0; i < users.length; i++) {
text += users[i] + "<br>";
}
document.write(text)
//Here in above code we get all users name using for loop we didn't need to write line by line code for all users
+ 6
Use additional materials :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
Search codeplayground, set language to web and search for loops, you'll find plenty of useful examples.
+ 5
for (let var = 0;var < 8;var++){
if (var%2==0){
dostuff();
}
}
+ 3
I appreciate your help. I guess part of the reason for not understanding loops is because I haven't thought of/found a project to include them in. I mostly use functions, DOM methods and if statements in my JavaScript. I haven't done any coding that would make me even think of using a loop(especially since I don't understand them entirely).