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
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.
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 value5 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};89// You can print the whole object to see what's inside10console.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.
1const book = {2 title: "The Great Adventure",3 author: "Jane Doe",4 pages: 2505};67// Accessing properties using dot notation (most common)8console.log("Book Title:", book.title); // Output: Book Title: The Great Adventure9console.log("Book Author:", book.author); // Output: Book Author: Jane Doe1011// Accessing properties using bracket notation12console.log("Number of Pages:", book["pages"]); // Output: Number of Pages: 2501314// Modifying (changing) a property15book.pages = 280; // Change the 'pages' property to 28016console.log("Updated Pages:", book.pages); // Output: Updated Pages: 2801718// Adding a new property19book.publicationYear = 2023; // Add a new 'publicationYear' property20console.log("Publication Year:", book.publicationYear); // Output: Publication Year: 20232122// Removing a property23delete book.author; // Remove the 'author' property24console.log("Book object after deleting author:", book); // Output: { title: 'The Great Adventure', pages: 280, publicationYear: 2023 }
const car = { make: "Toyota" };console.log(car.model); // This will output 'undefined'
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.
// This is the most common and easiest wayconst product = {name: "Laptop",price: 1200};
// This also creates an empty object// Then you add properties one by oneconst product = new Object();product.name = "Laptop";product.price = 1200;
// This is the most common and easiest wayconst product = {name: "Laptop",price: 1200};
// This also creates an empty object// Then you add properties one by oneconst 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.
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.
1const user = {2 id: 101,3 username: "coder_kid",4 email: "coder@example.com",5 isActive: true6};
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.
1user.lastLogin = new Date().toLocaleDateString(); // Add a 'lastLogin' property2console.log("User with new login time:", user);
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.
1user.isActive = false; // User logs out, so set isActive to false2console.log("User status updated:", user.isActive);
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.
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 key5 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.
| Method | Description | Example 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
Which of the following is the correct way to create an empty JavaScript object?
How do you access the 'color' property of an object named 'car'?
What will be the value of person.city after running this code?
const person = { name: "John", age: 25 }; person.city = "New York";
If you try to access a property that does not exist in an object, what will JavaScript return?
Quick Reference
Quick Reference
- 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.keyto 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.
- 7
undefined— Accessing a non-existent property will result inundefined, not an error. - 8Methods — Functions stored as object properties are called methods, allowing objects to have behaviors.
- 9
Object.keys()— A useful method to get an array of all property names (keys) from an object. - 10
deleteOperator — Usedelete object.propertyto 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.