Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript getOwnPropertyNames()

The Object.getOwnPropertyNames() method can retrieve the property names of an object.

Syntax

Object.getOwnPropertyNames(object)

List all Object Properties

This example retrieves all properties of an object:

Example

// Create an Object
const person = {
  firstName: “John”,
  lastName : “Doe”,
  language : “EN”
};

// Get all Properties
Object.getOwnPropertyNames(person);

Object.getOwnPropertyNames() will also include properties that are non-enumerable.

Example

// Create an Object
const person = {
  firstName: “John”,
  lastName : “Doe”,
  language : “EN”
};

// Set the language Property not enumerable
Object.defineProperty(person, “language”, {enumerable:false});

// Get all Properties
Object.getOwnPropertyNames(person);

JavaScript Object.keys()

The Object.keys() method can

  • retrieve enumerable property names of an object.

Syntax

Object.keys(object)

List Enumerable Object Properties

This example uses Object.keys() instead of Object.getOwnPropertyNames().

Example

// Create an Object
const person = {
  firstName: “John”,
  lastName : “Doe”,
  language : “EN”
};

// Change the “language” Property
Object.defineProperty(person, “language”, {enumerable:false});

// Get all Enumerable Properties
Object.keys(person);
Note:
The getOwnPropertyNames() method returns all properties, while the Object.keys() method returns only enumerable properties. If object properties are defined with enumerable: false, both methods will return the same result.

Adding Getters and Setters

The Object.defineProperty() method can also be used to define getters and setters.

Example

//Create an object
const person = {firstName:“John”, lastName:“Doe”};

// Define a getter
Object.defineProperty(person, “fullName”, {
  get: function () {return this.firstName + ” “ + this.lastName;}
});

A Counter Example

Example

// Define object
const obj = {counter:0};

// Define setters
Object.defineProperty(obj, “reset”, {
  get : function () {this.counter = 0;}
});
Object.defineProperty(obj, “increment”, {
  get : function () {this.counter++;}
});
Object.defineProperty(obj, “decrement”, {
  get : function () {this.counter–;}
});
Object.defineProperty(obj, “add”, {
  set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, “subtract”, {
  set : function (i) {this.counter -= i;}
});

// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

Prototype Properties

JavaScript objects inherit properties from their prototype.

The delete keyword does not remove inherited properties, but if a property is deleted from the prototype, it will affect all objects that inherit from that prototype.