惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
P
Privacy & Cybersecurity Law Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 热门话题
C
Cybersecurity and Infrastructure Security Agency CISA
S
Security Affairs
Latest news
Latest news
Security Latest
Security Latest
N
News and Events Feed by Topic
Spread Privacy
Spread Privacy
P
Proofpoint News Feed
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
The Exploit Database - CXSecurity.com
The Last Watchdog
The Last Watchdog
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
V
Vulnerabilities – Threatpost
Hacker News - Newest:
Hacker News - Newest: "LLM"
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
The Cloudflare Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
GRAHAM CLULEY
博客园_首页
S
Secure Thoughts
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
AWS News Blog
AWS News Blog
腾讯CDC
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Register - Security
The Register - Security
N
News and Events Feed by Topic
A
Arctic Wolf
MongoDB | Blog
MongoDB | Blog
爱范儿
爱范儿
Project Zero
Project Zero
A
About on SuperTechFans
罗磊的独立博客
云风的 BLOG
云风的 BLOG
Know Your Adversary
Know Your Adversary
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
K
Kaspersky official blog
L
LINUX DO - 最新话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
How to Use forEach() to Iterate an Array in JavaScript
Dmitri Pavlutin · 2019-07-03 · via Dmitri Pavlutin Blog

What's the usual thing you do with an array? Iterate through its items! This is where forEach() array method can be helpful.

This post describes how to use forEach() array method to iterate items of an array in JavaScript. Plus, you'll will read about forEach() best practices like correct handling of this and how to iterate array-like objects.

1. Basic forEach example

array.forEach() method iterates over the array items, in ascending order, without mutating the array.

The first argument of forEach() is the callback function called for every item in the array. The second argument (optional) is the value of this set in the callback.


array.forEach(callback [, thisArgument])


Let's see how forEach() works in practice.

colors array has 3 items. Let's use forEach() to log to console each color:


const colors = ['blue', 'green', 'white'];

function iterate(item) {

console.log(item);

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"


Open the demo.

iterate is the callback function. colors.forEach(iterate) executes iterate function for each item in colors.

3 invocation of iterate() function are perfomed:

  • iterate('blue')
  • iterate('green')
  • iterate('white')

That's how, in a few words, forEach() method works.

2. Index of the iterated element

array.forEach(callback) executes the callback function with 3 arguments: the current iterated item, the index of the iterated item and the array instance itself.


array.forEach(callback(item [, index [, array]]))


Let's access the index of each item in the colors array:


const colors = ['blue', 'green', 'white'];

function iterate(item, index) {

console.log(`${item} has index ${index}`);

}

colors.forEach(iterate);

// logs "blue has index 0"

// logs "green has index 1"

// logs "white has index 2"


Open the demo.

iterate() is called with the iterated item and the index arguments. The callback is executed 3 times:

  • iterate('blue', 0)
  • iterate('green', 1)
  • iterate('white', 2)

3. Access the array inside the callback

To access the array itself during the iteration, you can use the 3rd parameter inside the callback function.

Let's log the message The last iteration! when JavaScript executes the last iteration on the array items.


const colors = ['blue', 'green', 'white'];

function iterate(item, index, array) {

console.log(item);

if (index === array.length - 1) {

console.log('The last iteration!');

}

}

colors.forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"

// logs "The last iteration!"


Open the demo.

The 3rd parameter array inside the callback function is the array on which forEach() method was called on.

4. this inside the callback

Let's run the following example in a browser, and pay attention to the value of this:


const letters = ['a', 'b', 'c'];

function iterate(letter) {

console.log(this === window); // true

}

letters.forEach(iterate); // logs 3 times "true"


Open the demo.

this inside iterate() equals to window, which is the global object in the browser environment. Follow regular function invocation to get more information.

In some situations, you might need to set this to an object of interest. Just indicate this object as the second argument:


array.forEach(callback, thisArgument)


Let's implement a Unique class, which always holds an unique list of items:


class Unique {

constructor(items) {

this.items = items;

}

append(newItems) {

newItems.forEach(function(newItem) {

if (!this.items.includes(newItem)) {

this.items.push(newItem);

}

}, this);

}

}

const uniqueColors = new Unique(['blue']);

console.log(uniqueColors.items); // => ['blue']

uniqueColors.append(['red', 'blue']);

console.log(uniqueColors.items); // => ['blue', 'red']


Open the demo.

newItems.forEach(function() {}, this) is called with the second argument pointing to this, i.e. the instance of Unique class.

Inside the callback of forEach(), this points also to an instance of Unique. Now it's safe to access this.items.

For the above example using an arrow function as the callback of forEach() would be better (check the demo). The arrow function preserves the value of this from the lexical scope, so there's no need to use the second argument on forEach().

5. forEach skips empty slots

forEach() skips the empty slots of the array (named sparse array).


const sparseArray = [1, , 3];

sparseArray.length; // => 3

sparseArray.forEach(function(item) {

console.log(item);

}); // logs 1, 3


Open the demo.

sparseArray contains 1, an empty slot, and 3. forEach() iterates over 1 and 3, but skips the empty slot.

6. Iterate array-like objects using forEach

forEach() can iterate over array-like objects using an indirect call:


const arrayLikeColors = {

"0": "blue",

"1": "green",

"2": "white",

"length": 3

};

function iterate(item) {

console.log(item);

}

Array.prototype.forEach.call(arrayLikeColors, iterate);

// logs "blue"

// logs "green"

// logs "white"


Open the demo.

arrayLikeColors is an array-like object. To iterate over its items, you have to call forEach() indirectly: Array.prototype.forEach.call(...).

Alternatively, you can transform the array-like object into an array using Array.from(), then iterate:


const arrayLikeColors = {

"0": "blue",

"1": "green",

"2": "white",

"length": 3

};

function iterate(item) {

console.log(item);

}

Array.from(arrayLikeColors).forEach(iterate);

// logs "blue"

// logs "green"

// logs "white"


Open the demo.

7. When to use forEach()

forEach() fits to iterate array items, without breaking, and having simultaneously some side-effect.

Side-effects examples are a mutation of an outer scope variable, I/O operations (HTTP requests), DOM manipulations, logging to console ,and alike.

For example, let's select all input elements from the DOM and use forEach() to clear them:


const inputs = document.querySelectorAll('input[type="text"]');

inputs.forEach(function(input) {

input.value = '';

});


The side effect in the callback function is clearing the value of the input field.

Keep in mind that you cannot normally break the iteration of forEach() (other than a tricky way to throw an error to stop the iteration, which is a cheap hack). The method normally iterates over all the items.

If your case requires an early break from the cycle, a better option is the classic for or for..of.

When the array iteration computes a result, without side-effects, a better alternative is to select an array method like:

For example, let's determine if all numbers of an array are even.

The first solution involves forEach() method:


let allEven = true;

const numbers = [22, 3, 4, 10];

numbers.forEach(function(number) {

if (number % 2 === 1) {

allEven = false;

// Break here

}

});

console.log(allEven); // => false


Open the demo.

The code determines correctly if all numbers are even: since the array contains 3, the variable allEvent is false. The problem is the impossibility to break after finding the first odd number 3.

For this situation, a better alternative is array.every() method:


const numbers = [22, 3, 4, 10];

const allEven = numbers.every(function(number) {

return number % 2 === 0;

});

console.log(allEven); // => false


Open the demo.

array.every() makes the code shorter. Also .every() method breaks iterating after finding the first odd number — so the code skips unnecessary steps.

8. Conclusion

array.forEach(callback) method is a good way to iterate over all array items. Its first argument is the callback function, which is invoked for each item in the array with 3 arguments: item, index, and the array itself.

forEach() is useful to iterate over all array items, without breaking, involving simultaneously some side-effects. Otherwise, consider an alternative array method.

Have questions on how array.forEach() works? Write a comment and let's discuss!