What is the technical term for Object.keys()?
When understanding a new method or concept in JavaScript I believe it's great to start with the technical term and then attempt to explore further with real world examples.
The offical MDN technical term of the Object.keys() method is as follows:
“The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would”.
That was pretty easy to understand right? 🤔
A real world Object.keys example:
Lets explain this method in more detail starting with the example below:
const person = {
name: "Ryan Test",
age: 42,
location: "Sydney"
};
console.log(Object.keys(object1));
// expected output: Array ["name", "age", "location"]
The object has three keys named name
, age
and location
these all nested inside the person object.
What makes the technical term more complicated is that keys
also can be known as properties
.
So when you follow this through in more detail when using the Object.keys() method you are asking to get the given object keys back in an array of strings.
What Syntax does Object.keys follow?
The Syntax for Object.keys is relatively simple:
Syntax:
Object.keys(obj)
Parameters Used:
- obj : Is simply the object whose enumerable properties are to be returned.
Return value: This is simply an array of strings that represent all the enumerable properties of the given object.
Looking for some additional Object.keys() examples?
Here are some different examples provided by MDN. Be sure to try these out in the developer console or your text editor of choice:
// simple array
const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
// array like object
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
// array like object with random key ordering
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']
// getFoo is a property which isn't enumerable
const myObj = Object.create({}, {
getFoo: {
value: function () { return this.foo; }
}
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']
Conclusion
We hope that this short post provided you with some real world examples as how to use the JavaScript Object.keys() method.
As a JavaScript developer you may not need to use this everyday but its useful to understand fully so that you can easily reference how this can be useful in the future.
If you are looking for more posts on JavaScript and Web Development in general please visit and subscribe to the Learnstability blog for regular helpful posts.