Looping through array elements and string characters in JavaScript
by danielkwood
HTML
<html>
<head>
<title>Using for loops with arrays and strings</title>
<script src="script.js"></script>
</head>
<body>
</body>
</html>
JavaScript
var users = ["homer", "marge", "bart", "lisa", "maggie"];
// We can use for loops to work through each element in an array.
// This loop will go through each user in the users array and display on a separate line in the console. We can use the length method to make sure the loop stops once it reaches the end of the array
for(i = 0; i < users.length; i++){
console.log(users[i]);
}
// This is another method (where x will represent each user in the users array).
for(x of users){
console.log(x);
}
// Here is an example of using a for loop to search for an element in an array
for(i = 0; i < users.length; i++){
if(users[i] == "bart"){
console.log("I found Bart!");
}
}
// Here is an example of using a for loop to find an element in an array and modify it
for(i = 0; i < users.length; i++){
if(users[i] == "lisa"){
users[i] = "lisasimpson";
}
}
// We can also use for loops to work through each character in a string.
var myString = "Doh!";
// This will display each character in the myString variable on a new line in the console.
for(i = 0; i < myString.length; i++){
console.log(myString[i]);
}