JavaScript set forEach() Method is used to execute a provided function once for each element in the Set
. It also maintains insertion order.
set1.forEach (function(element) { //code })
JavaScript set forEach() example
Simple example code using the Set.prototype.forEach()
method. Inside the function, we simply log the value of each element to the console.
<!DOCTYPE html>
<html>
<body>
<script >
const mySet = new Set([1, 2, 3, 4, 5]);
mySet.forEach(function(value) {
console.log(value);
});
</script>
</body>
</html>
Output:
Here are a few more examples of using forEach()
in JavaScript:
1. Adding Elements to an Array
const numbers = [1, 2, 3];
const newNumbers = [];
numbers.forEach(function(number) {
newNumbers.push(number * 2);
});
console.log(newNumbers); // [2, 4, 6]
2. Modifying an Existing Array
const numbers = [1, 2, 3];
numbers.forEach(function(number, index, array) {
array[index] = number * 2;
});
console.log(numbers); // [2, 4, 6]
3. Using Arrow Functions
const numbers = [1, 2, 3];
const newNumbers = [];
numbers.forEach(number => {
newNumbers.push(number * 2);
});
console.log(newNumbers); // [2, 4, 6]
Do comment if you have any doubts or suggestions on this set method topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version