JavaScript Code


JavaScript Set forEach()


Set forEach() method

forEach() method runs a given function for each element in the Set.

set.forEach(someFunction);
set.forEach(someFunction, thisArg);

someFunction can be a callback function or it can have the syntax from any of the following.

() => { code }
(value) => { code }
(value, key) => { code }
(value, key, set) => { code }

function() { code }
function(value) { code }
function(value, key) { code }
function(value, key, set) { code }
  • set is a Set of elements.
  • forEach is method name.
  • someFunction is a function.
  • value is the current value of the element.
  • key is the current key of the element.
  • thisArg is value passed to someFunction and can be accessed as this in the the function.

Examples

1. Iterate over entries of the vowels set.

function printElement(value) {
    console.log(value);
}

const fruits = new Set(['apple', 'banana', 'cherry']);
fruits.forEach(printElement);

Copyright @2022