Skip to content
Related Articles

Related Articles

Improve Article

JavaScript | Object.getOwnPropertyNames() Method

  • Last Updated : 17 Sep, 2021

The Object.getOwnPropertyNames() method in JavaScript is standard built-in objects which returns all property that are present in a given object.
Syntax: 
 

Object.getOwnPropertyNames(obj)

Parameters: This method accept single parameter as mentioned above and described below: 
 

  • obj: This parameter holds the object whose enumerable and non-enumerable properties are to be returned.

Return value: This method returns an array of strings that corresponds to the properties found directly in the given object.
Below examples illustrate the Object.getOwnPropertyNames() method in JavaScript:
Example 1: 
 

javascript




const gfg = {
  val1: "Geek1",
  val2: "Geek2",
  val3: "Geek3",
  val4: "Geek4"
};
console.log(Object.getOwnPropertyNames(gfg));
 
var gfg2 = { val1: 'Geek1', val2: 'Geek2', val3: 'Geek3' }; 
console.log(Object.getOwnPropertyNames(gfg2).sort());
   
Object.getOwnPropertyNames(gfg2).
        forEach(function(val, idx, array) { 
  console.log(val + ' -> ' + gfg2[val]); 
   
});

Output: 
 

Array ["val1", "val2", "val3", "val4"]
Array ["val1", "val2", "val3"]
"val1 -> Geek1"
"val2 -> Geek2"
"val3 -> Geek3"

Example 2: 
 



javascript




function ParentClass() {}
ParentClass.prototype.inheritedMethod = function() {};
 
function ChildClass() {
  this.prop = 5;
  this.method = function() {};
}
ChildClass.prototype = new ParentClass;
ChildClass.prototype.prototypeMethod = function() {};
 
console.log(
  Object.getOwnPropertyNames(
    new ChildClass()
  )
);
 
var my_obj = Object.create({}, {
  getFoo: {
    value: function() { return this.foo; },
    enumerable: false
  }
});
my_obj.foo = 1;
 
console.log(Object.getOwnPropertyNames(my_obj).sort());

Output: 
 

Array ["prop", "method"]
Array ["foo", "getFoo"]

Supported Browsers: The browsers supported by Object.getOwnPropertyNames() method are listed below: 
 

  • Google Chrome 5.0 and above
  • Edge 12 and above
  • Firefox 4 and above
  • Internet Explorer 9.0 and above
  • Mozilla 4.0 and above
  • Opera 12 and above
  • Safari 5.0 and above

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :