forEach Method (Set) (JavaScript)

Performs the specified action for each element in a set.


setObj.forEach(callbackfn[, thisArg])  


Required. A Set object.

Required. callbackfn accepts up to three arguments. The function that forEach calls one time for each element in the set.

Optional. An object that the this keyword can refer to in the callbackfn function. If thisArg is omitted, undefined is used as the this value.


If the callbackfn argument is not a function object, a TypeError exception is thrown.


The syntax of the callback function is as follows:

function callbackfn(value, key, setObj)

You can declare the callback function by using up to three parameters, as shown in the following table.

Callback argument Definition
value A value contained in the set.
key A value contained in the set. A set has no keys, so this value is the same as value.
setObj The Set object to traverse.


The following example shows how to use forEach. The callbackfn argument includes the code for the callback function.

var s = new Set();  


s.forEach(function(item, sameItem, s) {  
    document.write("Size of the set object is: " + s.size + "<br />");  
    document.write("Deleting item: " + item + "<br />");  

// Output:  
// Size of the set object is: 3  
// Deleting item: scale  
// Size of the set object is: 2  
// Deleting item: 10  
// Size of the set object is: 1  
// Deleting item: 5  


The following example shows that you can also retrieve members from a set by passing only a single parameter to the callback function.

var s = new Set();  
s.add("Thomas Jefferson");  
s.add("founding father");  

s.forEach(function (item) {  
    document.write(item.toString() + ", ");  

// Output:  
// Thomas Jefferson, 1776, founding father,  


Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). See Version Information.
Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards. Not supported in Windows 8.