Tutorials Tonight
Follow Us

JavaScript Objects: everything you need to know


In this tutorial, you will know everything about objects in javascript with lots of real-life examples.

What is a Javascript object?

A Javascript object is a collection of properties and methods. It is a way to group data together and store it in a structured way.

The data in objects are stored in key-value pairs. Where each key-value pair is called a property. The key is the name of the property and the value is the value of the property.

The key of an object is a string while the value can be any data type, including another object.

javascript object

Here is an object of a person:

var person = {
  firstName: "John",
  lastName : "Doe",
  age      : 50
};

Javascript is an object-based language, everything in javascript is an object or can be made an object using a new keyword. Example:


How to create object in javascript

Javascript objects can be created in many different ways. Some of the ways are:

  1. javascript object literal
  2. javascript Object.create method
  3. javascript object constructor
  4. object using class

Among all ways to create objects in javascript, the most common way is the object literal.


1. Javascript Object Literal

The simplest way to create an object in javascript is using the object literal.

It is a comma separated key-value pair enclosed in curly braces ({}) assigned to a variable.

To create an empty object just assign a curly brace to a variable:

let person = {};

The object defined above is an empty object.

The properties are added to an object in form of key-value pair, the key should be a string and the value could be any data type.

2 key-value pairs are separated by a comma (,).

let person = {
  // adding properties to an object
  firstName: "John",
  lastName : "Doe",
  age      : 50
};
// checking type
console.log(typeof person);

Here, the object person has three properties: 'firstname', 'lastname', and 'age'.


2. Using Object.create method

The Object.create() method is used to create an object from an existing object. It creates a new object with the same properties as the existing object.

It uses an existing object as a prototype of the newly created object

Object.create(object);

You can pass the reference object in the method as the first parameter. This will create a new object whose values can be changed later.

Example

// prototype object
let person = {
  firstname: "steve",
  lastname: "jobs",
  fullName: function() {
    return "My name is " + this.firstname + " " + this.lastname;
  }
}
// create a new object
let newPerson = Object.create(person);
// change the value of the new object
newPerson.firstname = "John";
newPerson.lastname = "Smith";

console.log(newPerson.fullName());
▶ Run the code

Output:

javascript object using object create method

3. Javascript Object Constructor

Another way to create an object is using the object constructor.

The object constructor is a function that is used to create an object. It is defined using the new keyword.

The object constructor is used to create an object with a specific set of properties and methods.

If you want to create multiple objects of the same type then it is better to use the object constructor.

Here are the steps to create an object using the object constructor:

  1. Create a function that will be used to create an object.
  2. The function should have a parameter that is the object properties.
  3. Now use the new keyword with the function to create an object.

Example

// creating a function to create an object

function person(firstname, lastname, age) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.age = age;
}

// creating an object using the function
let person1 = new person("steve", "jobs", 25);
console.log(person1);

let person2 = new person("john", "smith", 35);
console.log(person2);
▶ Run the code

Output:

javascript-constructor-object

To add a method to an object, use the prototype property of the function.

The prototype property is used to add methods to an object that is shared by all the objects created using the function.

Example

// creating a function to create an object
function person(firstname, lastname, age) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.age = age;
}

person.prototype.fullName = function() {
  return "My name is " + this.firstname + " " + this.lastname;
}

let person1 = new person("steve", "jobs", 25);

console.log(person1.fullName());

4. Javascript Object Using Class

Class was introduced in ES6. It is a syntactical sugar for creating an object constructor.

The class is used to create an object constructor. It is defined using the class keyword.

There is difference between the class and the object constructor. All the difference is in their syntax.

Example

// creating a class to create an object
class person {
  constructor(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
  }

  fullName() {
    return "My name is " + this.firstname + " " + this.lastname;
  }
}

// creating an object
let person1 = new person('John', 'Smith');

console.log(person1.fullName());
▶ Run the code

Output:

javascript object using class

Accessing properties of Object

There are two ways to access the properties of an object.

  1. Using the dot operator.
  2. Using the bracket operator.

1. dot operator

Using the dot operator, you can access the properties of an object by writing the object name followed by a dot and the property name.

objectName.propertyName

The dot operator is most commonly used to access the properties of an object.

Example

let car = {
  name: "Ford",
  color: "Black",
}

// accessing the property
console.log(car.name);
console.log(car.color);

2. bracket operator

Another way to access the properties of an object is using the bracket operator.

objectName[propertyName]

It accesses the properties of an object by writing the object name followed by the bracket and the property name as a string.

Note: If you want to access the value of a property whose name is a variable or property name is a space separated string, then you can use the bracket operator.

Example

let car = {
  name: "Ford",
  color: "Black"
}

// accessing the property
console.log(car["name"]);
console.log(car["color"]);

Adding properties to an Object

You can add a new property to an existing object simply by object name followed by a dot and the property name and assigning the value to the property.

Example

let car = {
  name: "Ford",
  color: "Black"
}

console.log(car);

// adding a new property
car.model = "Mustang";
console.log(car.model);

Alternatively, you can use square bracket notation to add a new property to an object.

Example

let car = {
  name: "Ford",
  color: "Black"
}

console.log(car);

// adding a new property
car['model'] = "Mustang";
console.log(car.model);

Deleting properties from an Object

You can delete a property from an object by using the delete operator.

Example

let car = {
  name: "Ford",
  color: "Black",
  model: "Avenger"
}
console.log(car.model);

// deleting a property
delete car.model;
console.log(car.model);

Looping through an Object

Here we have discussed 4 different ways to loop through an object.

1. Using for...in loop

The for...in loop access the properties of an object by iterating through the object.

Method 1

let car = {
  name: "Ford",
  color: "Black",
  model: "Avenger"
}

// looping through the object
for (let key in car) {
  console.log(key, car[key]);
}

2. Using Object.keys() loop

The Object.keys() method returns an array of a given object's property names. Which can be used to loop through the object.

Method 2

let car = {
  name: "Ford",
  color: "Black",
  model: "Avenger"
}

// looping through the object
for (let key of Object.keys(car)) {
  console.log(key, car[key]);
}

3. Using Object.values() loop

The Object.values() method returns an array of a given object's property values. Which gives us direct access to the values of the object.

Method 3

let car = {
  name: "Ford",
  color: "Black",
  model: "Avenger"
}

// looping through the object
for (let value of Object.values(car)) {
  console.log(value);
}

4. Using Object.entries() loop

The Object.entries() method returns an array of a given object's property names and values.

Example

let car = {
  name: "Ford",
  color: "Black",
  model: "Avenger"
}

// looping through the object
for (let entry of Object.entries(car)) {
  console.log(entry);
}

Javascript object Method

object methods are the functions that are defined inside the object and operate on it to perform a certain task.

object method is part of the object in the form of a key-value pair.

let Money = {
  earning: 12000,
  spent: 9000,
  remaining: function () {
      return this.earning - this.spent + " is remaining money.";
    }
}

To access the object method write the method name followed by the object name connected with a dot. Here is an example:

var restMoney = money.remaining();

Check Working example.

let money = {
  earning: 12000,
  spent: 9000,
  remaining: function () {
    return this.earning - this.spent + " is remaining money.";
    }
  }
document.getElementById("output").innerHTML = money.remaining();
▶ Run the code

Javascript array of objects

An array of objects is a collection of objects. Apart from a single object, you can create an array of objects to store multiple objects.

To access the properties of these objects you can simply loop through the array.

In the real world, you will generally get an array of objects. Example HTMLColllection, DOM, FormData, etc.

Consider an example of an array of students, where each student is an object itself having properties 'name', 'roll' and 'marks'.

var student = {
  name: "std4",
  roll: 4,
  marks: 68
}

Now let there be 5 students in the class, so you simply add all student object in an array and loop through the array to get desired property.

Example

var students = [
  {
    name: "std1",
    roll: 1,
    marks: 66
  },
  {
    name: "std2",
    roll: 2,
    marks: 58
  },
  {
    name: "std3",
    roll: 3,
    marks: 76
  },
  {
    name: "std4",
    roll: 4,
    marks: 80
  },
  {
    name: "std5",
    roll: 5,
    marks: 54
  }
];

// looping through array
for (let i = 0; i < students.length; i++) {
  console.log(students[i].name);
}
▶ Run the code

this keyword in javascript object

this keyword in an object represents the object itself. It is used to access the properties of the object. When you say this.propertyName it means object.propertyName.

In the example below the sum is a method in 'number' object which is using this keyword to access properties of its parent element.

var number = {
  num1: 10,
  num2: 15,
  sum: function(){
    return this.num1 + this.num2
  }
}
console.log(number.sum());
▶ Run the code

Conclusions

In this tutorial, we have covered everything about objects in javascript. We have seen 4 ways to create an object, 2 ways to access the properties of an object, 4 ways to loop through an object, deleting properties of an object, adding properties to an object, etc.


Points to remember:

  1. Javascript object is a container that holds properties in form of key-value pair.
  2. There are 4 ways to create an object in javascript: object literal, object constructor, object.create method and object using class.
  3. Properties of a javascript object can be accessed in 2 different methods: using the dot operator and using a square bracket.
  4. this keyword inside a javascript object refers to the object itself.