JavaScript - Reflect.ownKeys() Method
The Reflect.ownKeys() method is used to return the array of all the own property keys of an object, including non-enumerable properties. It is similar to Object.getOwnPropertyNames() and Object.getOwnPropertySymbols() in that it creates an array from the combined output of these two methods. This method is useful when you need to iterate over every property of an object, regardless of their enumerability.
It can also be used to retrieve both string and symbol keys, something that Object.keys() cannot accomplish. Object.keys() and Reflect.enumerate() include inherited properties, whereas Reflect.ownKeys() does not.
Syntax
Following is the syntax of JavaScript Reflect.ownKeys() method −
Reflect.ownKeys( obj )
Parameters
This method accepts only one parameter. The same are described below −
Return value
This method returns an array of the target oject own property keys.
Examples
Example 1
Let's look at the following example, where we are going to use the Reflect.ownKeys() on a object with a string keys.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {
car: 'RS6',
model: 2024
};
const keys = Reflect.ownKeys(x);
document.write(JSON.stringify(keys));
</script>
</body>
</html>
If we execute the above program, it will displays a text on the webpage.
Example 2
Consider another scenario where we are going to use the non-enumerable property.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = {};
Object.defineProperty(x, 'WELCOME', {
value: 1,
enumerable: false
});
document.write(JSON.stringify(Reflect.ownKeys(x)));
</script>
</body>
</html>
On executing the above script, it will displays a text on the webpage.
Example 3
In the following example, we are going to use the Reflect.ownKeys() to retrieve all the keys of the array.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
const x = ['11', '22', '33'];
const y = Reflect.ownKeys(x);
document.write(JSON.stringify(y));
</script>
</body>
</html>
When we execute the above script, the output window will pop up, displaying the text on the webpage.