JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Objects


In JavaScript, almost everything is an object. An object is simply a collection of properties, where each property is defined as a key–value pair. The key (also called property name) is usually a string, and the value can be any valid JavaScript data type, such as a number, string, boolean, array, function, or even another object.

Objects allow developers to group related data and behavior in a structured way. For example, instead of keeping a person’s first name, last name, and age in three separate variables, you can combine them into one object.

Objects are the foundation of JavaScript programming because they are used in many areas: representing data, working with the DOM, creating classes, building APIs, and more.

Creating Objects in JavaScript

There are multiple ways to create objects, and understanding each method is important as you move from beginner to advanced JavaScript.

1. Object Literal

The most common and simplest way is using curly braces {}.

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 25,
  isStudent: true
};

console.log(person.firstName); // John

Here, person is an object with four properties. Each property is written as key: value.

2. Using the new Object() Constructor

This method uses the built-in Object constructor.

const car = new Object();
car.brand = "Toyota";
car.model = "Camry";
car.year = 2024;

console.log(car.model); // Camry

Though valid, this style is less common because object literals are shorter and more readable.

3. Constructor Function

Before ES6 classes, developers used functions to create multiple objects of the same type.

function Student(name, roll) {
  this.name = name;
  this.roll = roll;
}

const student1 = new Student("Alice", 101);
console.log(student1.name); // Alice

Here, this refers to the newly created object.

4. ES6 Classes

Introduced in ES6 (2015), classes provide a cleaner syntax to create objects.

class Animal {
  constructor(type, sound) {
    this.type = type;
    this.sound = sound;
  }
}

const dog = new Animal("Dog", "Bark");
console.log(dog.sound); // Bark

Although classes look different, under the hood they still use prototypes, as JavaScript is a prototype-based language.

Accessing Object Properties

There are two main ways to access object properties:

  1. Dot Notation

console.log(person.firstName); // John
  1. Bracket Notation

console.log(person["lastName"]); // Doe

Bracket notation is useful when:

  • The property name contains spaces or special characters.

  • The property name is stored in a variable.

const key = "age";
console.log(person[key]); // 25

Adding and Modifying Properties

Objects in JavaScript are dynamic, meaning you can add or change properties at any time.

person.country = "USA";   // Add new property
person.age = 26;          // Modify existing property

console.log(person.country); // USA
console.log(person.age);     // 26

Deleting Properties

The delete keyword removes a property from an object.

delete person.isStudent;

console.log(person.isStudent); // undefined

Nested Objects

Objects can hold other objects as values, creating a nested structure.

const student = {
  name: "Rahul",
  marks: {
    math: 90,
    science: 85
  }
};

console.log(student.marks.math); // 90

This is useful for representing real-world data in a structured format.

Objects with Methods

A function defined inside an object is called a method.

const calculator = {
  add: function(a, b) {
    return a + b;
  },
  subtract(a, b) {
    return a - b; // Short method syntax
  }
};

console.log(calculator.add(5, 3));      // 8
console.log(calculator.subtract(10, 4)); // 6

Here, add and subtract are methods of the calculator object.

Looping Through Objects

Since objects are collections of properties, you often need to loop through them.

Using for...in

for (let key in person) {
  console.log(key + " : " + person[key]);
}

This loop goes through each property in the object.

Using Built-in Object Methods

JavaScript provides several methods for working with object keys and values:

  • Object.keys(obj) → returns an array of property names.

  • Object.values(obj) → returns an array of property values.

  • Object.entries(obj) → returns an array of [key, value] pairs.

console.log(Object.keys(person));   // ["firstName", "lastName", "age", "country"]
console.log(Object.values(person)); // ["John", "Doe", 26, "USA"]
console.log(Object.entries(person));
/*
[
  ["firstName", "John"],
  ["lastName", "Doe"],
  ["age", 26],
  ["country", "USA"]
]
*/

Object References

Objects in JavaScript are stored by reference, not by value.

const obj1 = { a: 10 };
const obj2 = obj1; // obj2 references the same object

obj2.a = 20;
console.log(obj1.a); // 20

Both obj1 and obj2 point to the same memory location. This is different from primitive values like numbers or strings, which are copied by value.

Built-in Object Methods

JavaScript provides many useful methods for objects. Some important ones are:

  • Object.assign(target, source) → copies properties from one object to another.

  • Object.freeze(obj) → makes an object immutable (cannot add, modify, or delete properties).

  • Object.seal(obj) → prevents adding or deleting properties, but allows modifying existing ones.

  • Object.hasOwn(obj, prop) → checks if a property exists directly on the object.

Example:

const user = { name: "Sam" };
const extra = { age: 30 };

const merged = Object.assign({}, user, extra);
console.log(merged); // { name: "Sam", age: 30 }

Object.freeze(user);
user.name = "Tom"; // ignored
console.log(user.name); // Sam

Summary of the Tutorial

  • JavaScript objects are collections of key–value pairs.

  • They can be created using literals, constructors, functions, or classes.

  • Properties can be accessed with dot or bracket notation.

  • Objects can hold data and behavior (methods).

  • You can loop through objects with for...in or Object methods.

  • Objects are mutable and stored by reference.

  • JavaScript provides built-in methods like Object.assign, Object.freeze, and Object.seal for working with objects.

Objects are central to JavaScript programming. Understanding how they work lays the foundation for learning advanced concepts like prototypes, inheritance, and object-oriented programming in JavaScript.


Practice Questions

  1. Create an object named book with properties: title, author, and pages. Then, log the author property using dot notation.

  2. Create the same object book as above, but access the title property using bracket notation.

  3. Add a new property publisher to the book object created in question 1, and assign it a value of your choice. Then, log the entire object.

  4. Modify the pages property of the book object to a new number, and log the updated value.

  5. Delete the author property from the book object. Then, check if it exists using in or Object.hasOwn() method.

  6. Create a nested object student with properties: name and marks. marks should itself be an object with math and science scores. Log the math score.

  7. Add a method named fullName to an object person with firstName and lastName properties. The method should return the full name. Call the method and log the result.

  8. Loop through the student object from question 6 using for...in and print all property names and values.

  9. Use Object.keys(), Object.values(), and Object.entries() on the book object. Log the output of each method.

  10. Demonstrate object reference behavior: Create an object original = {a: 5}. Assign copy = original. Modify copy.a to 10 and log both original.a and copy.a to show how objects are stored by reference.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top