Loops with Arrays
In this tutorial, we will learn how to use loops to iterate over arrays in JavaScript.
In JavaScript, arrays are used to store multiple values in a single variable. They are a special type of object that can hold multiple values at once.
Basic Syntax
Here is the basic syntax for creating an array in JavaScript:
let fruits = ["apple", "banana", "cherry"];In this example, we have created an array called fruits that contains three elements: 'apple', 'banana', and 'cherry'.
Using Loops with Arrays
There are several ways to iterate over the elements of an array in JavaScript. Some of them are:
for Loop
The for loop is a common way to iterate over the elements of an array. Here is an example:
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}This will output:
apple
banana
cherryforEach Method
The forEach method is another way to iterate over the elements of an array. Here is an example:
let fruits = ["apple", "banana", "cherry"];
fruits.forEach(function (fruit) {
console.log(fruit);
});This will output:
apple
banana
cherryfor...of Loop
The for...of loop is a modern way to iterate over the elements of an array. Here is an example:
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}This will output:
apple
banana
cherryConclusion
- In JavaScript, arrays are used to store multiple values in a single variable.
- There are several ways to iterate over the elements of an array, such as using a
forloop, theforEachmethod, or thefor...ofloop.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on