JavaScript Objects: Properties and Methods
Understand JavaScript objects, properties, methods, dot notation and bracket notation with beginner-friendly examples.
Describe a value with properties
An object groups related information using named properties. This example describes one book:
const book = {
title: "Small Web Projects",
pages: 180,
available: true
};
Read and update properties
Use dot notation when the property name is known in your code. Bracket notation is useful when the property name is stored in a variable.
console.log(book.title);
book.available = false;
const field = "pages";
console.log(book[field]);
Add a method
A method is a function stored as an object property. It can use this to refer to the object that owns it.
const user = {
name: "Sam",
greet() {
return `Hello, ${this.name}`;
}
};
Create an updated object without changing the original
The spread syntax copies an object’s own enumerable properties into a new object. Put a changed property after the spread to replace its old value in the copy:
const updatedBook = {
...book,
available: false
};
This is a shallow copy: nested objects are still shared references. For simple flat objects, the pattern is a convenient way to preserve the original while creating an updated version.
Object questions
Can a const object be changed?
const prevents assigning a different object to the same variable. It does not freeze the object, so its properties can still be updated unless the object is frozen separately.
When should I use an object instead of an array?
Use an object when values have descriptive names, such as a book’s title and page count. Use an array when you need an ordered collection of values, such as a list of book titles.