getOwnPropertyNames() method - JavaScript Tutorial

getOwnPropertyNames() method

BLUF: This tutorial on getOwnPropertyNames() method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: getOwnPropertyNames() method

Understanding getOwnPropertyNames() method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The Object.getOwnPropertyNames function provides an array containing all properties associated directly with a specified object, excluding any non-enumerable properties that utilize symbols.

Syntax:

Example

Object.getOwnPropertyNames(obj)

Parameter:

obj : This refers to the object from which both its enumerable and non-enumerable own properties will be retrieved.

Return value:

This approach yields an array of strings that represent the properties located directly on the object.

Browser Support:

Chrome 5
Edge Yes
Firefox 4
Opera 12

Example 1

Example

const object1 = {
  a: 0,
  b: 1,
  c: 2,
};
console.log(Object.getOwnPropertyNames(object1));

Output:

Output

["a", "b", "c"]

Example 2

Example

var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.getOwnPropertyNames(obj).sort()); // logs '0,1,2'

// Logging property names and values using Array.forEach

Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
  console.log(val + ' -> ' + obj[val]);

});

Output:

Output

["0", "1", "2"]
 "0 -> a"
 "1 -> b"
 "2 -> c"

Example 3

Example

function Pasta(grain, size, shape) {
    this.grain = grain; 
    this.size = size; 
    this.shape = shape; 
}
var spaghetti = new Pasta("wheat", 2, "circle");
var names = Object.getOwnPropertyNames(spaghetti).filter(CheckKey);
document.write(names); 
 // Check whether the first character of a string is 's'. 
function CheckKey(value) {
    var firstChar = value.substr(0, 1); 
    if (firstChar.toLowerCase() == 's')
        return true; 
    else
         return false; }

Output:

Output

size,shape

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience