JavaScript Objects Get Certified
Objects are one of the core building blocks of JavaScript. They let you group related data and behavior together using key-value pairs.
In this lesson, you will learn how to create objects, access and
update their properties, define methods, work with nested data,
and use helpful built-in methods like
Object.keys(), Object.values(), and
Object.entries().
Creating Objects
The most common way to create an object is with an object literal — curly braces containing properties.
What this code does: An object literal creates a new object with key-value pairs. You can mix different value types (strings, numbers, booleans) in the same object.
const book = {
title: "The Silent River",
author: "Maya Chen",
pages: 312,
isAvailable: true
};
console.log(book);
const book = { starts an object literal and stores it in the constant book. The curly braces define a new plain object.title: "The Silent River", creates a property named title whose value is a string.author: "Maya Chen", adds a second string property for the author’s name.pages: 312, stores a number. Object properties can hold any type of value.isAvailable: true adds a Boolean flag. No trailing comma is required after the last property.}; closes the object and ends the statement.console.log(book); prints the whole object so you can see all four key-value pairs together.Accessing Properties
You can read a property with dot notation or bracket notation.
What this code does: Dot notation is the usual way to read a property. Bracket notation is useful when the key is stored in a variable or contains special characters.
const car = {
brand: "Toyota",
model: "Corolla",
year: 2021
};
console.log(car.brand);
console.log(car["model"]);
const key = "year";
console.log(car[key]);
const car = { begins a new object literal stored in car.brand: "Toyota", sets the brand.model: "Corolla", sets the model name.year: 2021 sets the year as a number.}; ends the object literal.console.log(car.brand); reads the brand property with the familiar dot syntax and prints Toyota.console.log(car["model"]); does the same thing using square brackets. The key is written as a string. This prints Corolla.const key = "year"; puts the property name into a variable. Bracket notation is required when the key is dynamic.console.log(car[key]); looks up the property whose name is stored in key and prints 2021.Adding and Updating Properties
You can add new properties or change existing ones at any time.
What this code does: Assigning to a property updates it if it exists, or creates it if it doesn’t.
Both color and the updated year appear when the object is logged.
const phone = {
brand: "Samsung",
model: "Galaxy S23"
};
phone.color = "black";
phone.year = 2023;
console.log(phone);
const phone = { starts an object with two initial properties.brand: "Samsung", sets the brand.model: "Galaxy S23" sets the model.}; ends the object literal.phone.color = "black"; creates a brand-new property named color and gives it the value "black".phone.year = 2023; adds a year property. If the property had already existed, this line would have overwritten its previous value.console.log(phone); prints the object, which now contains four properties: brand, model, color, and year.Deleting Properties
The delete operator removes a property from an object.
What this code does: delete removes a property completely.
After deletion, the key no longer exists on the object.
const user = {
name: "Alex",
age: 29,
tempToken: "xyz-123"
};
delete user.tempToken;
console.log(user);
const user = { begins an object that holds user data.name: "Alex", stores the user’s name.age: 29, stores the age.tempToken: "xyz-123" is a property we intend to remove later.}; ends the object literal.delete user.tempToken; completely removes the tempToken property from the object. After this line the key no longer exists.console.log(user); prints the object. Only name and age remain.Methods
When a property’s value is a function, it is called a method.
What this code does: A method is a function stored as a property.
Calling greeter.sayHello() runs the function and prints the greeting.
const greeter = {
sayHello: function () {
console.log("Hello from the object!");
}
};
greeter.sayHello();
const greeter = { starts an object that will hold a method.sayHello: function () { assigns a function to the property sayHello. A property whose value is a function is called a method.console.log("Hello from the object!"); is the code that runs when the method is called.} closes the function.}; ends the object literal.greeter.sayHello(); looks up the method and invokes it with the trailing parentheses. The greeting is printed to the console.Method Shorthand
Modern JavaScript lets you write methods more concisely by
omitting the function keyword.
What this code does: Method shorthand omits the function keyword.
checkAvailability() is cleaner and behaves the same as the longer form.
const library = {
booksInStock: 128,
checkAvailability() {
return this.booksInStock > 0;
}
};
console.log(library.checkAvailability());
const library = { begins an object that will contain both data and a method.booksInStock: 128, stores the current number of books.checkAvailability() { defines a method using the concise shorthand syntax. The function keyword is omitted.return this.booksInStock > 0; uses this to read the object’s own booksInStock property and returns true when the value is greater than zero.} closes the method.}; ends the object literal.console.log(library.checkAvailability()); invokes the method and prints the Boolean result (true in this case).Using this Inside Methods
Inside a regular method, this refers to the object
the method was called on, letting you access that object’s other
properties.
What this code does: Methods can update the object’s own state via this.
Spending 50 reduces the balance; trying to spend 500 returns an insufficient-funds message.
const wallet = {
balance: 200,
spend(amount) {
if (amount > this.balance) {
return "Insufficient funds";
}
this.balance -= amount;
return "New balance: " + this.balance;
}
};
console.log(wallet.spend(50));
console.log(wallet.spend(500));
const wallet = { starts an object that models a simple wallet.balance: 200, stores the current amount of money.spend(amount) { creates a method that accepts the amount to spend. Method shorthand is used.if (amount > this.balance) { compares the requested amount with the object’s own balance using this.return "Insufficient funds"; exits the method immediately when there is not enough money.} closes the conditional.this.balance -= amount; subtracts the spent amount from the object’s own balance property.return "New balance: " + this.balance; builds a success message that includes the updated balance.} closes the method.}; ends the object literal.console.log(wallet.spend(50)); calls the method with a safe amount. The balance becomes 150 and the success message is printed.console.log(wallet.spend(500)); tries to spend more than the remaining balance and therefore prints Insufficient funds.Nested Objects
An object’s property value can itself be another object, allowing you to model more complex, structured data.
What this code does: Objects can contain other objects (nesting).
Access nested values by chaining: employee.address.city.
const employee = {
name: "Priya Nair",
department: "Engineering",
address: {
city: "Austin",
state: "TX"
}
};
console.log(employee.address.city);
const employee = { begins the top-level object.name: "Priya Nair", stores the employee’s name.department: "Engineering", stores the department name.address: { creates a property whose value is itself another object.city: "Austin", is a property of the inner address object.state: "TX" is the second property of the nested object.} ends the address object.}; ends the employee object.console.log(employee.address.city); walks down the chain: first the address property, then the city property inside it. The output is Austin.Checking If a Property Exists
The in operator checks whether a property exists on
an object, and hasOwnProperty() checks whether it
exists directly on the object itself (not inherited).
What this code does: Check whether a property exists with the in operator
or hasOwnProperty(). Both return true/false without throwing if the key is missing.
const ticket = {
eventName: "Jazz Night",
seatNumber: "12B"
};
console.log("eventName" in ticket);
console.log("price" in ticket);
console.log(ticket.hasOwnProperty("seatNumber"));
const ticket = { starts a simple ticket object.eventName: "Jazz Night", stores the event title.seatNumber: "12B" stores the seat identifier.}; ends the object literal.console.log("eventName" in ticket); uses the in operator. Because the property exists, the result is true.console.log("price" in ticket); checks a key that was never defined. The result is false.console.log(ticket.hasOwnProperty("seatNumber")); asks whether the property belongs directly to the object (not inherited). The answer is true.Property Shorthand
If a variable’s name matches the property name you want, you can skip repeating it.
What this code does: Property shorthand lets you write { orderId, total }
when the variable names match the desired keys. The function returns a compact order object.
function createOrder(orderId, total) {
return { orderId, total };
}
console.log(createOrder("ORD-501", 89.99));
function createOrder(orderId, total) { defines a factory function that receives an order ID and a total amount.return { orderId, total }; uses the concise property shorthand. Because the parameter names match the desired property names, writing orderId is enough; JavaScript expands it to orderId: orderId.} closes the function body.console.log(createOrder("ORD-501", 89.99)); invokes the function and prints the resulting object { orderId: "ORD-501", total: 89.99 }.Computed Property Names
You can use an expression as a property name by wrapping it in square brackets inside an object literal.
What this code does: Computed property names use brackets in the object literal.
The value of fieldName becomes the key, so the promo object gets a discountCode property.
const fieldName = "discountCode";
const promo = {
[fieldName]: "SUMMER25",
validUntil: "2026-09-01"
};
console.log(promo);
const fieldName = "discountCode"; holds the name that will become a property key.const promo = { begins the object that will use a computed property name.[fieldName]: "SUMMER25", evaluates the expression inside the brackets and uses the resulting string as the property name. The property is therefore named discountCode.validUntil: "2026-09-01" is a normal static property.}; ends the object literal.console.log(promo); prints the finished object, which contains both the computed key and the ordinary key.Object.keys(), Object.values(), and Object.entries()
These built-in methods let you extract an object’s keys, values, or both as arrays, which is especially useful for looping over an object’s contents.
What this code does: Object.keys, Object.values, and
Object.entries turn an object’s contents into arrays you can inspect or loop over.
const scoreboard = {
Alice: 92,
Ben: 87,
Chloe: 95
};
console.log(Object.keys(scoreboard));
console.log(Object.values(scoreboard));
console.log(Object.entries(scoreboard));
const scoreboard = { begins an object that maps names to scores.Alice: 92, stores Alice’s score.Ben: 87, stores Ben’s score.Chloe: 95 stores Chloe’s score.}; ends the object literal.console.log(Object.keys(scoreboard)); returns an array of the property names: ["Alice", "Ben", "Chloe"].console.log(Object.values(scoreboard)); returns an array of the property values: [92, 87, 95].console.log(Object.entries(scoreboard)); returns an array of two-element arrays, each containing a key and its value.
What this code does: Loop over key-value pairs with for...of and
Object.entries. Each iteration gives you the name and score to print.
const scoreboard = {
Alice: 92,
Ben: 87,
Chloe: 95
};
for (const [name, score] of Object.entries(scoreboard)) {
console.log(name + ": " + score);
}
const scoreboard = { recreates the object used in the previous example.Alice: 92,Ben: 87,Chloe: 95};for (const [name, score] of Object.entries(scoreboard)) { obtains an array of entries and immediately destructures each pair into the variables name and score.console.log(name + ": " + score); builds a readable string for every entry and prints it.} closes the loop body.Copying Objects
Simply assigning an object to a new variable copies the
reference, not the object itself. To create an actual independent
copy, use the spread operator (...) or
Object.assign().
What this code does: The spread operator creates a shallow copy.
Changing copiedSettings.fontSize does not affect the original object.
const originalSettings = { theme: "dark", fontSize: 14 };
const copiedSettings = { ...originalSettings };
copiedSettings.fontSize = 18;
console.log(originalSettings.fontSize);
console.log(copiedSettings.fontSize);
const originalSettings = { theme: "dark", fontSize: 14 }; creates the source object.const copiedSettings = { ...originalSettings }; uses the spread operator to create a new object that contains the same own enumerable properties. The two objects are now independent at the top level.copiedSettings.fontSize = 18; changes a property on the copy only.console.log(originalSettings.fontSize); still prints 14, proving the original was not affected.console.log(copiedSettings.fontSize); prints 18.Note that this creates a shallow copy — if a property’s value is itself an object, both copies will still share a reference to that nested object.
Practical Example
Let’s build a small product catalog entry using several object features together.
What this code does: A factory function builds objects with properties and methods.
getTotalValue uses this to multiply price by quantity for the product.
function createProduct(name, price, quantity) {
return {
name,
price,
quantity,
getTotalValue() {
return this.price * this.quantity;
}
};
}
const product = createProduct("Wireless Mouse", 25, 40);
console.log(product.getTotalValue());
function createProduct(name, price, quantity) { defines a function that will return a ready-to-use product object.return { begins the object that the factory builds.name, uses the parameter of the same name.price, likewise copies the price parameter.quantity, copies the quantity parameter.getTotalValue() { adds a method with the concise syntax.return this.price * this.quantity; multiplies the object’s own price by its own quantity.} closes the method.}; closes the object literal.} closes the function.const product = createProduct("Wireless Mouse", 25, 40); calls the factory and stores the resulting object.console.log(product.getTotalValue()); invokes the method, which computes 25 × 40 and prints 1000.Common Mistakes With Objects
- Using an arrow function for a method that needs
thisto refer to the object. - Forgetting that copying an object with
= otherObjectcopies the reference, not the actual data. - Using dot notation with a property name that contains spaces or special characters, instead of bracket notation.
- Assuming a shallow copy also duplicates nested objects, when it only copies references to them.
- Forgetting quotes around string keys that include spaces or start with a number.
Best Practices for Objects
- Use
constfor objects you don’t intend to reassign, since their contents can still be modified. - Prefer method shorthand syntax for cleaner object method definitions.
- Use
Object.keys(),Object.values(), orObject.entries()instead of manually looping over properties withfor...in. - Use the spread operator for simple shallow copies, and a dedicated deep-clone approach when nested objects also need to be copied independently.
- Keep related data grouped together in an object instead of scattering it across many separate variables.
Quick Summary
- Objects store data as key-value pairs, created using object literal syntax.
- Properties can be accessed with dot notation or bracket notation.
- A property whose value is a function is called a method, and
thisrefers to the object the method belongs to. Object.keys(),Object.values(), andObject.entries()help you work with an object’s contents.- Copying an object with
=copies a reference; use the spread operator for an actual (shallow) copy. - Object property values can be nested objects, arrays, or even other functions.
Try It Yourself
Modify the object below. Try adding a new property, a new method,
or looping over its entries with Object.entries().
What this code does: Practice example: add properties or methods, or try
Object.entries(), then click Test My Code to see the result.
const recipe = {
name: "Tomato Soup",
servings: 4,
scaleServings(multiplier) {
return this.servings * multiplier;
}
};
console.log(recipe.scaleServings(2));
const recipe = { begins a simple recipe object.name: "Tomato Soup", stores the recipe title.servings: 4, stores the original number of servings.scaleServings(multiplier) { defines a method that accepts a scaling factor.return this.servings * multiplier; multiplies the object’s own servings by the supplied multiplier and returns the result.} closes the method.}; ends the object literal.console.log(recipe.scaleServings(2)); scales the servings by 2 and prints 8. Try adding more properties or methods and re-running the code.Tip: If you find yourself managing several separate variables that all describe the same “thing” — like a name, price, and quantity for one product — that’s usually a strong signal they belong together in a single object.
Understanding objects is essential before moving on to arrays, classes, and more advanced JavaScript concepts.
🧪 Test Your JavaScript Code
Edit the code on the left and click “Run Code” to see the console output on the right.
Click “Run Code” to see the output here.
Code Explanation
The complete example stays visible. Use Previous and Next to move through its logical blocks.
Select Next to begin exploring the code.