How to find keys of a hash in JavaScript?

In JavaScript, objects act as hash tables where you can store key-value pairs. To extract all keys from an object, use the built-in Object.keys() method, which returns an array of the object's property names.

Syntax

Object.keys(object)

Parameters

object: The object whose keys you want to retrieve.

Return Value

Returns an array of strings representing the object's own enumerable property names (keys).

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Find Hash Keys</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        }
        .result {
            font-size: 18px;
            font-weight: 500;
            color: green;
            margin: 10px 0;
        }
        .btn {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Find Keys of a Hash in JavaScript</h1>
    <div class="result"></div>
    <button class="btn">DISPLAY KEYS</button>
    <h3>Click the button to display the object keys</h3>
    
    <script>
        let resEle = document.querySelector(".result");
        let obj = {
            firstName: "Rohan",
            lastName: "Sharma",
            age: 22,
            city: "Mumbai"
        };
        
        document.querySelector(".btn").addEventListener("click", () => {
            let keys = Object.keys(obj);
            resEle.innerHTML = "Object keys are: " + keys.join(", ");
        });
    </script>
</body>
</html>

Output

When you click the "DISPLAY KEYS" button, the output will be:

Object keys are: firstName, lastName, age, city

Using Object.keys() in Console

let person = {
    name: "Alice",
    age: 30,
    profession: "Developer"
};

let keys = Object.keys(person);
console.log(keys);
console.log("Number of keys:", keys.length);
['name', 'age', 'profession']
Number of keys: 3

Key Points

  • Object.keys() only returns enumerable own properties, not inherited properties
  • The order of keys follows the same order as a for...in loop
  • It returns an empty array for objects with no enumerable properties
  • Works with any object, including arrays (returns array indices as strings)

Conclusion

Object.keys() is the standard method to retrieve all keys from a JavaScript object. It returns an array of strings that you can iterate over or manipulate as needed.

Updated on: 2026-03-15T23:18:59+05:30

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements