The callback for Array.prototype.forEach is given three arguments, the current value, the index, and the array itself. val is the second argument (which should really be given a more appropriate name), so it is the index, which is a number.

This may help you understand:

let obj = {a: '1', b: '2'};

Object.keys(obj).forEach(function(key, idx, arr){
    console.log("Key:", key);
    console.log("Index:", idx);
    console.log("Original Array:", arr);
    console.log("Value:", obj[key]);
});

Alternatively, you can use Object.entries to directly access values (with destructuring):

let obj = {a: '1', b: '2'};

Object.entries(obj).forEach(function([key, val], idx, arr){
    console.log("Key:", key);
    console.log("Index:", idx);
    console.log("Original Array:", arr);
    console.log("Value:", val);
});

Answer from Unmitigated on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object › entries
Object.entries() - JavaScript - MDN Web Docs
// Using for...of loop const obj = { a: 5, b: 7, c: 9 }; for (const [key, value] of Object.entries(obj)) { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // Using array methods Object.entries(obj).forEach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" }); Polyfill of Object.entries in core-js ·
Discussions

Is Object.keys(obj).forEach really any better than for-in loop?
Yes, there is a difference. Object.keys() iterates over "own" properties, while for-in iterates over all enumerable properties, even those inherited in the prototype. Also, speed really isn't a concern for nearly all use cases. More on reddit.com
🌐 r/javascript
35
13
February 1, 2017
For...in vs Object.keys
It's largely preference or depending on whether or not you're dealing with a more imperative or more functional codebase. But you should at least be aware of the differences that go beyond style. Specifically, for..in will capture inherited keys whereas Object.keys sticks only to own properties. For example: var par = { prop1 : "some val" }; var obj = Object.create(par); obj.prop2 = "some other val"; for(key in obj){ console.log("Key: ", key) console.log("Value: ", obj[key]) } // ^ prop1 and prop2 Object.keys(obj).forEach((key)=>{ console.log("For Each Key: ", key) console.log("For Each Value: ", obj[key]) }) // ^ prop2 only More on reddit.com
🌐 r/javascript
24
14
April 24, 2018
How to loop through a plain JavaScript object with the objects as members - Stack Overflow
@MildFuzz actually it makes sense if you consider that JS objects do not necessary have numerical keys. You can't just iterate through an object. JS's for in is very similar to a traditional foreach. More on stackoverflow.com
🌐 stackoverflow.com
Iterate over object keys in node.js - javascript
Also remember that you can pass a second argument to the .forEach() function specifying the object to use as the this keyword. More on stackoverflow.com
🌐 stackoverflow.com
July 20, 2025
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object › keys
Object.keys() - JavaScript - MDN Web Docs
Object.keys() returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon object. This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-iterate-over-a-javascript-object
Iterate over a JavaScript object - GeeksforGeeks
function iterateObject() { let exampleObj = { book: "Sherlock Holmes", author: "Arthur Conan Doyle", genre: "Mystery" }; Object.keys(exampleObj).forEach(key => { const value = exampleObj[key]; console.log(`${key}: ${value}`); }); } iterateObject();
Published   October 14, 2025
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › foreach-object
Iterating Through an Object with `forEach()` - Mastering JS
May 29, 2020 - The Object.keys() function returns an array of the object's own enumerable properties. You can then iterate over each key in the object using forEach().
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › foreach-key-value
How to Use forEach() with Key Value Pairs - Mastering JS
July 14, 2021 - After that, you can then use forEach() to iterate through the keys, values, or entries: const obj = { name: 'Jean-Luc Picard', rank: 'Captain' }; // Prints "name Jean-Luc Picard" followed by "rank Captain" Object.keys(obj).forEach(key => { console.log(key, obj[key]); });
Find elsewhere
🌐
Flexiple
flexiple.com › javascript › loop-through-object-javascript
How to loop through objects keys and values in Javascript?
The for...in loop offers a simple ... functional approach, Object.keys() can be used to generate an array of the object's keys, which can then be iterated over using array methods like forEach....
🌐
DEV Community
dev.to › ljnce › foreach-object-values-object-keys-3n1f
forEach( ): Object.values / Object.keys - DEV Community
August 22, 2020 - If you want to cycle the element with forEach() method, you have three ways: Object.keys · Object.keys(array).forEach(function(key) { console.log(key); //--> 0 1 }); Object.values · Object.values(array).forEach(function(value) { console.log(value); //--> name: 'John' name: 'Mary' console.log(value.name); //--> John Mary }); .forEach ·
🌐
Hostman
hostman.com › tutorials › looping through objects’s keys and values in javascript
How to loop through objects keys and values in Javascript? | Hostman
August 25, 2025 - Object.getOwnPropertyNames(app... en // version: 1.0.0 · The Reflect.ownKeys() method retrieves all own properties of an object, including string keys and symbol keys....
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › for...in
for...in - JavaScript | MDN - MDN Web Docs
The for...in statement iterates over all enumerable string properties of an object (ignoring properties keyed by symbols), including inherited enumerable properties.
🌐
Reddit
reddit.com › r/javascript › for...in vs object.keys
r/javascript on Reddit: For...in vs Object.keys
April 24, 2018 -

Hey all, this is solely for for my own curiosity, but what would be preferred in any given situation while iterating over an object, "for...in", or "Object.keys(obj).forEach()"?

I generally favor "for...in", but it occurred to me the .forEach() method may work just as well.

Example:

var obj = { prop1 : "some val", prop2 : "some other val"};

for(key in obj){

console.log("Key: ", key)

console.log("Value: ", obj[key])

}

Object.keys(obj).forEach((key)=>{

console.log("For Each Key: ", key)

console.log("For Each Value: ", obj[key)

})

🌐
Inspirnathan
inspirnathan.com › posts › 140-iterating-through-objects-in-javascript
Iterating Through Keys and Values of Objects in JavaScript
July 21, 2022 - I'm going to go ahead and use Array.forEach since it seems like cleanest approach. ... const obj = { pizzas: 1, donuts: 2, potatoes: 3 }; Object.keys(obj).forEach(key => { console.log(key); }) /* OUTPUT: pizzas donuts potatoes */
🌐
freeCodeCamp
freecodecamp.org › news › how-to-iterate-over-objects-in-javascript
Loop Through an Object in JavaScript – How to Iterate Over an Object in JS
November 7, 2024 - We can also use the key to get the value using bracket notation such as population[gender] as seen below: genders.forEach((gender) => { console.log(`There are ${population[gender]} ${gender}`); }) ... Before we move on, let's use this method to sum all the population by looping through so we know the total population: const population = { male: 4, female: 93, others: 10 }; let totalPopulation = 0; let genders = Object.keys(population); genders.forEach((gender) => { totalPopulation += population[gender]; }); console.log(totalPopulation); // 107
🌐
Medium
sunnygandhi01.medium.com › how-to-iterate-through-an-object-keys-and-values-in-javascript-d8bb464615fa
How to Iterate through an object keys and values in JavaScript. | by Sunnygandhi | Medium
January 13, 2021 - This method was introduced in ES8 and it is tottally opposite of Object.key(). This Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. const fruits : { Mango: 100, Apple: 10, Orange: 50, Kiwi: 5 };//This time we iterate over object values. Object.values(fruits).forEach( key => console.log(key));Output: 100 10 50 5 ·
Top answer
1 of 6
268

What you want is lazy iteration over an object or array. This is not possible in ES5 (thus not possible in node.js). We will get this eventually.

The only solution is finding a node module that extends V8 to implement iterators (and probably generators). I couldn't find any implementation. You can look at the spidermonkey source code and try writing it in C++ as a V8 extension.

You could try the following, however it will also load all the keys into memory

Object.keys(o).forEach(function(key) {
  var val = o[key];
  logic();
});

However since Object.keys is a native method it may allow for better optimisation.

Benchmark

As you can see Object.keys is significantly faster. Whether the actual memory storage is more optimum is a different matter.

var async = {};
async.forEach = function(o, cb) {
  var counter = 0,
    keys = Object.keys(o),
    len = keys.length;
  var next = function() {
    if (counter < len) cb(o[keys[counter++]], next);
  };
  next();
};

async.forEach(obj, function(val, next) {
  // do things
  setTimeout(next, 100);
});
2 of 6
26

Also remember that you can pass a second argument to the .forEach() function specifying the object to use as the this keyword.

// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
  // element is the name of the key.
  // key is just a numerical value for the array
  // _array is the array of all the keys

  // this keyword = secondArg
  this.foo;
  this.bar();
}, secondArg);
🌐
Envato Tuts+
code.tutsplus.com › home › coding fundamentals
How to Iterate Over Object Keys With JavaScript | Envato Tuts+
May 20, 2022 - In addition, you can't use iterator methods like map() and forEach(). If you do, you'll get a TypeError in every instance. Instead, use for...in to iterate over objects. This method iterates over all of the object's enumerable, non-symbol properties. In the following example, we use it to iterate over all three properties of obj, and for each property, we log a string consisting of the property name (i.e. its key) and its corresponding value.
🌐
Index.dev
index.dev › blog › javascript-object-iteration-methods
10 Effective Methods to Iterate Over JavaScript Objects
If you're working with a single object, you can't use this directly. ... for...of loop. You must first transform the item into an iterable structure, such as an array, in order to utilize it with it. const movie = { title: 'Inception', director: 'Christopher Nolan', year: 2010 }; for (const [key, value] of Object.entries(movie)) { console.log(`${key}: ${value}`); }
🌐
Atomizedobjects
atomizedobjects.com › blog › javascript › how-to-use-foreach-with-an-object-in-javascript
How to use forEach with an Object in JavaScript | Atomized Objects
As you can see this method of using Object.keys with forEach works because we get an array of all the keys in the object that when we iterate through using forEach we can use each key to perform a lookup on the original object to then get the value from as well.