How to List the Properties of a JavaScript Object

JavaScript is an object-oriented programming language that is used to build dynamic and interactive websites.

JavaScript objects are containers for storing key-value pairs of data, similar to a dictionary in Python or a HashMap in Java.

In this tutorial, we will take a closer look at the properties of a JavaScript object and learn how to list them.


What are Properties in JavaScript?

A property in JavaScript is a key-value pair that belongs to an object.

Properties are used to store data within an object and can be accessed or modified using the dot notation or square bracket notation.

For example, if we have an object called person, we can add properties to it like this:

let person = {};
person.name = "John";
person.age = 30;

Types of Properties in JavaScript

There are two types of properties in JavaScript: own properties and inherited properties.

Own properties are properties that belong directly to an object, while inherited properties are properties that are passed down from the object’s prototype.

Listing Properties of a JavaScript Object

There are several ways to list the properties of a JavaScript object, and each has its own advantages and disadvantages.

Here, we will look at three common methods for listing properties.

Method 1: for…in Loop

The for...in loop is a common method for listing the properties of an object.

This loop iterates through the object’s enumerable properties and returns the property names.

Here’s an example:

let person = {
  name: "John",
  age: 30,
  job: "developer"
};

for (let property in person) {
  console.log(property);
}

Output:

name
age
job

Object.keys() Method

The Object.keys() method is a built-in JavaScript function that returns an array of a given object’s own enumerable property names.

Here’s an example:

let person = {
  name: "John",
  age: 30,
  job: "developer"
};

console.log(Object.keys(person));

Output:

[ 'name', 'age', 'job' ]

Object.getOwnPropertyNames() Method

The Object.getOwnPropertyNames() method is similar to the Object.keys() method, but it returns an array of all the object’s own property names, including non-enumerable properties.

Here’s an example:

let person = {
  name: "John",
  age: 30,
  job: "developer"
};

console.log(Object.getOwnPropertyNames(person));

Output:

[ 'name', 'age', 'job' ]

Conclusion

In this tutorial, we have learned about the properties of a JavaScript object and how to list them.

Whether you use the for...in loop, the Object.keys() method, or the Object.getOwnPropertyNames() method, each method has its own benefits and limitations.

By understanding these methods, you will be able to effectively work with JavaScript objects and their properties.