← Back to Chapters

JavaScript Objects

? JavaScript Objects

? Quick Overview

In JavaScript, an object is a collection of related data and functionality represented as key–value pairs. Keys are called properties, and values can be anything: strings, numbers, booleans, arrays, other objects, or even functions (called methods).

Objects let you model real-world entities like a person, car, or student in a structured way, keeping data and behavior together.

? Key Concepts

  • Object literal – create objects using curly braces {}.
  • Properties – key–value pairs that store data inside an object.
  • Methods – functions stored as properties, often using this.
  • Accessing properties – using dot notation or bracket notation.
  • Nested objects – objects inside other objects.
  • Looping – iterate over keys with for...in and helpers like Object.keys().
  • Getters and setters – define computed / controlled properties.
  • Prototypes – shared properties and methods for all instances.
  • Object protection – use Object.freeze() and Object.seal() to limit changes.

? Syntax and Theory

The most common way to create an object is with the object literal syntax:

? View Code Example
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
isEmployed: true
};

Access properties using:

  • Dot notation: person.firstName
  • Bracket notation: person["lastName"]

Methods are just functions stored in properties:

? View Code Example
const user = {
name: "Alice",
greet: function() {
return "Hello, " + this.name + "!";
}
};

Under the hood, every object is linked to a prototype (e.g., Object.prototype or your own), from which it can inherit shared methods and properties.

? Code Examples

? Basic object creation and property access

? View Code Example
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
isEmployed: true
};

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

✏️ Modifying and adding properties

? View Code Example
person.age = 31;            // modify existing property
person.city = "New York";   // add new property

console.log(person);
/*
{
  firstName: "John",
  lastName: "Doe",
  age: 31,
  isEmployed: true,
  city: "New York"
}
*/

?️ Methods and the this keyword

? View Code Example
const user = {
name: "Alice",
greet: function() {
return "Hello, " + this.name + "!";
}
};

console.log(user.greet()); // Hello, Alice!

const car = {
brand: "Toyota",
start: function() {
return this.brand + " engine started.";
}
};

console.log(car.start()); // Toyota engine started.

? Nested objects

? View Code Example
const student = {
name: "Emily",
marks: {
math: 90,
science: 85
}
};

console.log(student.marks.science); // 85

? Looping through properties

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

? Useful helpers and object protection

? View Code Example
// Check if property exists
console.log("age" in person); // true

// Delete property
delete person.isEmployed;

// Object.keys and Object.values
console.log(Object.keys(person));   // ['firstName', 'lastName', 'age', 'city']
console.log(Object.values(person)); // ['John', 'Doe', 31, 'New York']

// Object.entries
console.log(Object.entries(person));
/*
[
  ['firstName', 'John'],
  ['lastName', 'Doe'],
  ['age', 31],
  ['city', 'New York']
]
*/

// Copying an object using spread operator
const newPerson = { ...person };
console.log(newPerson);

// Freezing an object to prevent changes
Object.freeze(newPerson);
newPerson.age = 40;       // This will not change the value
console.log(newPerson.age); // Still 31

? Creating and modifying a simple object

? View Code Example
const user2 = {};
user2.name = "Alice";
user2.age = 25;

delete user2.age;
console.log(user2); // { name: "Alice" }

? Getters and setters for computed properties

? View Code Example
const personWithFullName = {
firstName: "John",
lastName: "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
},
set fullName(name) {
const parts = name.split(" ");
this.firstName = parts[0];
this.lastName = parts[1];
}
};

personWithFullName.fullName = "Jane Smith";
console.log(personWithFullName.firstName); // Jane

? Prototypes and constructor functions

? View Code Example
function Animal(name) {
this.name = name;
}

Animal.prototype.speak = function() {
return this.name + " makes a noise.";
};

const dog = new Animal("Dog");
console.log(dog.speak()); // Dog makes a noise.

? Object protection with Object.freeze

? View Code Example
const config = {
debug: true
};

Object.freeze(config);
config.debug = false;      // Ignored in non-strict mode, error in strict mode

console.log(config.debug); // true

? Interactive Example

Try reading properties from a simple demoPerson object using bracket notation.

demoPerson = { firstName, lastName, age, city }

? Result

Waiting for input...

? Live Output and Explanation

? What do these examples print?

  • console.log(person.firstName); prints John because it reads the firstName property.
  • console.log(student.marks.science); prints 85 by going into the nested marks object.
  • console.log("age" in person); returns true if age is a direct or inherited property.
  • After Object.freeze(newPerson), changing newPerson.age has no effect, so it stays 31.
  • dog.speak() works because speak is defined on Animal.prototype and shared by all animals.

Together, these examples show how objects store data, how methods use this, how nested structures work, and how prototypes enable reuse.

? Tips and Best Practices

  • Use the this keyword in regular function methods to refer to the current object.
  • Use Object.freeze() to make configuration objects immutable.
  • Use the spread operator { ...obj } for quick shallow copies of objects.
  • Use Object.keys(obj), Object.values(obj) and Object.entries(obj) to work with object data more easily.
  • Use prototypes (or classes) to share methods between instances without duplicating code.
  • Prefer meaningful property names that clearly describe the data they hold.

? Try It Yourself

  • Create an object called book with properties: title, author, and year.
  • Access the author property of the book object using both dot and bracket notation.
  • Add a new property genre to the book object and assign it a value.
  • Write a method inside book called getSummary that returns a string summary of the book.
  • Loop through all properties of the book object and log their keys and values.
  • Check if the year property exists in the book object using the in operator.
  • Delete the genre property from the book object.
  • Use Object.keys() and Object.values() to get all keys and values of the book object.
  • Copy the book object into a new object called newBook using the spread operator.
  • Freeze the newBook object and try to change its title property. Observe that the value does not change.