3

How to forEach Over an Array in JavaScript

 2 years ago
source link: https://www.laravelcode.com/post/how-to-foreach-over-an-array-in-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to forEach Over an Array in JavaScript

  1125 views

  1 year ago

Javascript

 Use the forEach() Method

You can simply use the array's forEach() method to loop through all the items in an array using JavaScript. The forEach() method executes a provided function once for each array element.

The following example will display all the values in the cities array using foreach loop.

<script>
    // Sample array
    var cities = ["London", "Paris", "New York", "Amsterdam"];
    
    // Loop over array
    cities.forEach(function(value){
        document.write("<p>" + value + "</p>");
    });
</script>

The forEach() method does not modify the original array (i.e. the array on which it is called). However, the callback function, if invoked, may do so. The following example will modify the given array by squaring each of its value (multiplying it by itself).

<script>
    // Sample array
    var numbers = [1, 2, 3, 4, 5, 6];
    
    // Loop over array and squaring each value
    numbers.forEach(function(value, index, array){
        array[index] = value * value;
    });
    
    console.log(numbers); // Prints: [1, 4, 9, 16, 25, 36]
</script>
Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK