- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set.forEach() function in JavaScript
The forEach() function of the Set object accepts the name of a particular function and runs that function for every value in the current set. For Example, if you have written a function to print a value, if you use forEach() function it prints the value of every element in the set.
Syntax
Its Syntax is as follows
setObj.forEach()
Example
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> function sampleFunction(value){ document.writeln(value+","); } const setObj1 = new Set(); setObj1.add('Java'); setObj1.add('JavaFX'); setObj1.add('JavaScript'); setObj1.add('HBase'); setObj1.forEach(sampleFunction); document.write("<br>"); var sum = 0; function mathExample(value) { sum = value+sum; //document.write(value); } const setObj2 = new Set(); setObj2.add(172); setObj2.add(364); setObj2.add(885); setObj2.add(746); setObj2.forEach(mathExample); document.write("Sum of all elements in the set: "+sum); </script> </body> </html>
Output
Java, JavaFX, JavaScript, HBase, Sum of all elements in the set: 2167
Advertisements