What is the Object.keys function in JavaScript?

The Object.keys function in JavaScript is used to extract the keys of all the key-value pairs present in an object.

Syntax

Object.keys(object_name)

Parameters

The Object.keys function only takes in one argument:

  • object_name: The name of the object whose keys will be returned.

Return value

The Object.keys function returns an array containing the keys of all the key-value pairs stored in the prescribed object.

For an array, the Object.keys function returns a list of its non-empty indexes.

Example

The program below declares an object, which contains three key-value pairs and an array of four characters. Each key is the territory’s name, and the corresponding value is the territory’s capital city.

The Object.keys function is called on the array and the object containing key-value pairs, and the raw return value is printed using the console.log function.

Since the return value is an array, it can be enumerated upon and printed iteratively using a for loop, as shown below.

// Declare a sample object with key-value pairs
const sample_object = {
America: 'New York',
Japan: 'Tokyo',
Australia: 'Sydney'
};
const array = ["A","B","C"]
console.log("Return value of Object.keys(array):\n\n",Object.keys(array))
// Enumerate over the return value and print it
console.log("\nThe return value is enumerable and can be accessed via a for loop:\n")
for (val of Object.keys(array)) {
console.log(`${val}`);
}
// Print the return value of Object.keys
console.log("Return value of Object.keys(sample_object):\n\n",Object.keys(sample_object))
// Enumerate over the return value and print it
console.log("\nThe return value is enumerable and can be accessed via a for loop:\n")
for (territory of Object.keys(sample_object)) {
console.log(`${territory}`);
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved