Skip to content

Instantly share code, notes, and snippets.

@pajaydev
Last active April 5, 2024 01:47
Show Gist options
  • Save pajaydev/e8dfcbab883ce6742488c8b02e8f96ff to your computer and use it in GitHub Desktop.
Save pajaydev/e8dfcbab883ce6742488c8b02e8f96ff to your computer and use it in GitHub Desktop.
JS Objects : Object.keys vs for..in vs getOwnPropertyNames vs Object.entries

Object.keys vs for..in vs getOwnPropertyNames vs Object.entries

const language = {
  name: 'JavaScript',
  author: 'Brendan Eich'
};

// Inheriting from another object.
Object.setPrototypeOf(language, {createdAt: "Netscape"});


// make the author non enumerable.
Object.defineProperty(language, 'author', {
  enumerable: false
});

language.propertyIsEnumerable('author') // false

Object.keys

// returns the array of enumerable properties.
Object.keys(language); // ["name"]

Object.getOwnPropertyNames

// returns array of both enumerable and non enumerable properties
Object.getOwnPropertyNames(language); //["name", "author"]

for..in

Iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

for(let key in language){
  console.log(key)
};
// "name","createdAt"

Object.entries

// similar to Object.keys but it returns the array of keys and values.
for (let [key, value] of Object.entries(language)) {
  console.log(`${key}: ${value}`); // "name: JavaScript"
};
Comparison Object.keys Object.getOwnPropertyNames for in Object.entries
enumerable
non-enumerable
inherited

Inspired from this tweet https://twitter.com/mgechev/status/1248498467044917251/photo/1

@daeh
Copy link

daeh commented Jan 15, 2022

This is really useful. thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment