javascript

Object

Learn about JavaScript Objects, a fundamental data type for grouping related data using key-value pairs. Understand how to create, access, and modify object properties effectively.

9 min read 8 sections Tutorial
Share

In JavaScript, an Object is a special kind of data type. It helps you store many pieces of related information together in one place. You will learn how to create objects, put data into them, and get data out of them.

Object

Object

In JavaScript, an Object is a special kind of data type. It helps you store many pieces of related information together in one place. Think of it like a container that holds different items, where each item has a label. You will learn how to create objects, put data into them, and get data out of them in this tutorial.

What is a JavaScript Object?

A JavaScript Object is a collection of properties, where each property is a key-value pair used to store and organize data.

Key-Value Pairs

Objects store data as a list of names (keys) and their corresponding values.

Dynamic Content

You can add, change, or remove properties from an object even after it's created.

Versatile Storage

Objects can store different types of values, including numbers, strings, booleans, and even other objects.

Real-World Data

They are perfect for representing real-world things like a user, a car, or a product with many details.

Creating Your First Object

Getting Started

Creating Your First Object

The easiest way to create an object is by using curly braces {}. Inside these braces, you list your key-value pairs. Each pair has a key (like a label) and a value (the data it holds). Keys are usually strings, and values can be any data type, like a number or text. You separate each key-value pair with a comma.

javascript
1// Create an object named 'person'
2const person = {
3 firstName: "Alice", // 'firstName' is the key, "Alice" is the value (a string)
4 lastName: "Smith", // 'lastName' is the key, "Smith" is the value
5 age: 30, // 'age' is the key, 30 is the value (a number)
6 isStudent: false // 'isStudent' is the key, false is the value (a boolean)
7};
8
9// You can print the whole object to see what's inside
10console.log(person);

Don't Forget the Commas!

A common mistake is forgetting to put a comma , between each key-value pair in an object. This will cause an error in your code. Always remember to separate them!

Accessing and Modifying Object Properties

Accessing and Modifying Object Properties

Once you have an object, you will want to get the data stored inside it. You can do this using two main ways: dot notation (.) or bracket notation ([]). Dot notation is usually simpler and more common. Bracket notation is useful when your key has spaces or is stored in a variable.

javascript
1const book = {
2 title: "The Great Adventure",
3 author: "Jane Doe",
4 pages: 250
5};
6
7// Accessing properties using dot notation (most common)
8console.log("Book Title:", book.title); // Output: Book Title: The Great Adventure
9console.log("Book Author:", book.author); // Output: Book Author: Jane Doe
10
11// Accessing properties using bracket notation
12console.log("Number of Pages:", book["pages"]); // Output: Number of Pages: 250
13
14// Modifying (changing) a property
15book.pages = 280; // Change the 'pages' property to 280
16console.log("Updated Pages:", book.pages); // Output: Updated Pages: 280
17
18// Adding a new property
19book.publicationYear = 2023; // Add a new 'publicationYear' property
20console.log("Publication Year:", book.publicationYear); // Output: Publication Year: 2023
21
22// Removing a property
23delete book.author; // Remove the 'author' property
24console.log("Book object after deleting author:", book); // Output: { title: 'The Great Adventure', pages: 280, publicationYear: 2023 }
✗ BadWrong (Accessing Missing Property)
const car = { make: "Toyota" };
console.log(car.model); // This will output 'undefined'
✓ GoodCorrect (Checking for Property)
const car = { make: "Toyota" };
if (car.model === undefined) {
console.log("Model is not defined.");
} else {
console.log(car.model);
}

Different Ways to Create Objects

Different Ways to Create Objects

While object literals ({}) are the most common and easiest way to create objects, there are other methods. You can also use the new Object() constructor or Object.create(). For beginners, sticking to object literals is usually the best approach because it is simple and clear. Understanding other methods helps you read other people's code.

Object Literal (Recommended)
// This is the most common and easiest way
const product = {
name: "Laptop",
price: 1200
};
VS
Using new Object()
// This also creates an empty object
// Then you add properties one by one
const product = new Object();
product.name = "Laptop";
product.price = 1200;

When to Use What

Always prefer the object literal ({}) syntax for creating objects. It's more readable, concise, and generally faster. The new Object() method is rarely used in modern JavaScript.

Using Objects for Real-World Data

Using Objects for Real-World Data

Objects are incredibly useful for representing complex things in your code. For example, you can use an object to describe a user on a website, a product in a store, or an event in a calendar. This helps keep related data organized and easy to manage.

1

Define a User Object

Start by creating an object to hold information about a user. This makes it easy to pass all user details around together.

javascript
1const user = {
2 id: 101,
3 username: "coder_kid",
4 email: "coder@example.com",
5 isActive: true
6};
2

Add a New Detail

If you need to store more information about the user later, you can easily add new properties to the existing object. This makes objects very flexible.

javascript
1user.lastLogin = new Date().toLocaleDateString(); // Add a 'lastLogin' property
2console.log("User with new login time:", user);
3

Update an Existing Detail

You can change any property's value whenever needed. For example, if the user's status changes, you can update it directly.

javascript
1user.isActive = false; // User logs out, so set isActive to false
2console.log("User status updated:", user.isActive);
4

Loop Through Object Properties

Sometimes you need to look at all the keys or values in an object. You can use a for...in loop to go through each property. This is useful for displaying all details.

javascript
1console.log("User Details:");
2for (let key in user) {
3 // 'key' will be 'id', 'username', 'email', etc.
4 // user[key] gets the value for that key
5 console.log(`${key}: ${user[key]}`);
6}

Accessing Undefined Properties

If you try to access a property that does not exist in an object, JavaScript will return undefined. This usually won't crash your program immediately, but it can lead to unexpected behavior if you try to use that undefined value later in your code.

Object Methods and Properties

Object Methods and Properties

JavaScript provides some built-in methods on the Object type itself. These methods help you work with objects in powerful ways, like getting a list of all keys or values. They are very useful for more advanced object manipulation.

MethodDescriptionExample Output
`Object.keys(obj)`Returns an array of all the property names (keys) in the object.`["name", "age"]`
`Object.values(obj)`Returns an array of all the property values in the object.`["Max", 25]`
`Object.entries(obj)`Returns an array of `[key, value]` pairs for all properties.`[["name", "Max"], ["age", 25]]`
`Object.assign(target, source)`Copies all properties from one or more source objects to a target object.Creates a new combined object

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which of the following is the correct way to create an empty JavaScript object?

Quick Check

How do you access the 'color' property of an object named 'car'?

Quick Check

What will be the value of person.city after running this code? const person = { name: "John", age: 25 }; person.city = "New York";

Quick Check

If you try to access a property that does not exist in an object, what will JavaScript return?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Objects — Are a fundamental data type in JavaScript for storing collections of related data.
  • 2Key-Value Pairs — Objects store data as properties, each having a unique key (name) and an associated value.
  • 3Object Literal — The most common way to create an object is using curly braces {} and defining properties inside.
  • 4Dot Notation — Use object.key to access or modify properties with simple names.
  • 5Bracket Notation — Use object['key'] to access or modify properties, especially when keys have spaces or are in variables.
  • 6Dynamic — You can easily add, change, or remove properties from an object after it has been created.
  • 7undefined — Accessing a non-existent property will result in undefined, not an error.
  • 8Methods — Functions stored as object properties are called methods, allowing objects to have behaviors.
  • 9Object.keys() — A useful method to get an array of all property names (keys) from an object.
  • 10delete Operator — Use delete object.property to remove a property from an object.

Arrays

Learn about Arrays, another way to store collections of data in an ordered list.

Functions

Explore functions, which are blocks of code that can be stored and reused, often as object methods.

JSON

Understand JSON (JavaScript Object Notation), a text format based on objects for sending data over the web.

Classes

Discover Classes, a blueprint for creating objects with shared properties and methods.

You've Mastered Objects!

Congratulations! You now understand the basics of JavaScript Objects, how to create them, and how to work with their properties. Objects are a cornerstone of JavaScript programming, allowing you to organize your data effectively for more complex applications. Keep practicing, and you'll soon be building amazing things!

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning