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

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
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
How to loop through a plain JavaScript object with the objects as members - Stack Overflow
How can I loop through all members in a JavaScript object, including values that are objects? For example, how could I loop through this (accessing the "your_name" and "your_message&... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Iterate over object keys in node.js - Stack Overflow
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
🌐
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().
🌐
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.
🌐
Latenode
latenode.com › home › blog › development & programming › javascript for automation › how to iterate over a javascript object?
How to Iterate Over a JavaScript Object? - Latenode Blog
February 12, 2026 - Key Takeaways: JavaScript objects are not inherently iterable, but several methods exist for looping through their properties. The for...in loop is traditional but requires a hasOwnProperty() check, while newer methods like Object.entries() with map()/forEach(), Object.keys() with forEach(), and Object.values() offer more streamlined approaches.
🌐
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....
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-iterate-over-a-javascript-object
Iterate over a JavaScript object - GeeksforGeeks
object.keys() Method returns an array of keys of the object and forEach() method is an array method that allows you to iterate over each element in the array. JavaScript ·
Published   October 14, 2025
Find elsewhere
🌐
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)

})

🌐
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 => { ...
🌐
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
Here is an example of how to use Object.keys with forEach to get the key value pairs: const myObject = { someKey: "some value", hello: "World", js: "javascript foreach object", } Object.keys(myObject).forEach(key => { const value = myObject[key] console.log(key, value) // "someKey" "some value", "hello" "world", "js javascript foreach object" })
🌐
DEV Community
dev.to › ljnce › foreach-object-values-object-keys-3n1f
forEach( ): Object.values / Object.keys - DEV Community
August 22, 2020 - #javascript #beginners #tutorial #html · Hi!🙋‍♂️ · I wrote this article for show you this 3 forEach ways: Take this simply array: var array = [ { name: 'John' }, { name: 'Mary' } ]; If you want to cycle the element with forEach() method, you have three ways: Object.keys ·
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › for...in
for...in - JavaScript | MDN - MDN Web Docs
It is better to use a for loop with a numeric index, Array.prototype.forEach(), or the for...of loop, because they will return the index as a number instead of a string, and also avoid non-index properties. If you only want to consider properties attached to the object itself, and not its prototypes, you can use one of the following techniques: ... Object.keys will return a list of enumerable own string properties, while Object.getOwnPropertyNames will also contain non-enumerable ones. Many JavaScript style guides and linters recommend against the use of for...in, because it iterates over the entire prototype chain which is rarely what one wants, and may be a confusion with the more widely-used for...of loop.
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);
🌐
Go Make Things
gomakethings.com › the-es6-way-to-loop-through-objects-with-vanilla-javascript
The ES6 way to loop through objects with vanilla JavaScript | Go Make Things
March 9, 2018 - Then we run that through an Array.forEach() method. var lunch = { sandwich: 'ham', snack: 'chips', drink: 'soda', desert: 'cookie', guests: 3, alcohol: false, }; Object.keys(lunch).forEach(function (item) { console.log(item); // key console.log(lunch[item]); // value }); // returns "sandwich", "ham", "snack", "chips", "drink", "soda", "desert", "cookie", "guests", 3, "alcohol", false
🌐
Clubmate
clubmate.fi › javascript-manipulating-objects-with-object-keys
Common JavaScript array methods and Object.keys() – clubmate.fi
var nameObj = { first: 'Zaphod', last: 'Beeblebrox' } Object.keys(nameObj).forEach(function (key) { console.log(key + ': ' + nameObj[key]) }) // first: Zaphod // last: Beeblebrox
🌐
Byby
byby.dev › js-foreach-object
How to use forEach with object in JavaScript
January 1, 2023 - Using Object.values() to get an array of a given object’s own enumerable string-keyed property values. This means that it takes an object as an argument and returns an array containing the values of the properties that can be looped over with a for...in loop. var book = { title: "The Hitchhiker's Guide to the Galaxy", author: "Douglas Adams", genre: "science fiction", rating: 4.5 }; Object.values(book).forEach(function(value) { console.log(value); }); // The Hitchhiker's Guide to the Galaxy // Douglas Adams // science fiction // 4.5
🌐
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 */