How to use loop in javascript
There are several ways to loop in vanilla JavaScript. Here are a few examples:
for
loop:
for (let i = 0; i < 5; i++) {
console.log(i);
}
This will output the numbers 0 through 4. The for
loop has three parts: the initialization (let i = 0
), the condition (i < 5
), and the iteration (i++
). The loop will continue to run as long as the condition is true.
while
loop:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
This will also output the numbers 0 through 4. The while
loop will continue to run as long as the condition (i < 5
) is true.
do...while
loop:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
This will also output the numbers 0 through 4. The do...while
loop is similar to the while
loop, but it will always run at least once, because the code block is executed before the condition is checked.
There are also several array methods that allow you to loop over the elements of an array, such as forEach and map
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
This will output the numbers 1 through 5. The forEach
method takes a callback function as an argument, and it will execute the callback for each element in the array.
map :
In JavaScript, the map
method is used to apply a function to each element in an array, and create a new array with the results. It is a built-in method of the Array
object, and can be used like this:
const array = [1, 2, 3, 4, 5];
const doubled = array.map(x => x * 2);
// doubled is [2, 4, 6, 8, 10]
Here, the map
method is called on the array
object, and a function is passed as an argument. This function takes in an element x
from the array, and returns x * 2
. The map
method applies this function to each element in the array, and creates a new array with the results.
You can also pass a function with a more complex logic to the map
method:
const array = [1, 2, 3, 4, 5];
const squared = array.map(x => x * x);
// squared is [1, 4, 9, 16, 25]
The map
the method is a very useful array method, as it allows you to easily transform an array of values into a new array. It is often used in combination with other array methods, like filter
and reduce
, to perform more complex operations on arrays.