JavaScript Object Data Structure
A object in JavaScript is a key-value pair collection used to store structured data. Objects are one of the most fundamental and powerful data structures in JavaScript.
Common use cases:
- Modeling real-world entities: Represent users, products, or configurations.
- Dynamic properties: Add or update properties at runtime.
- Nesting: Store nested objects for complex structures.
- Flexible data access: Use dot or bracket notation to read/write data.
Quick Links
What You'll Learn
In this section, you’ll learn how to create objects, access and modify their properties, and use common object methods such as Object.keys(), Object.entries(), and more.
Understanding the Object Data Structure
The basic syntax for creating an object in JavaScript is:
const myObject = {
key1: value1,
key2: value2,
key3: value3,
};
const myObject = {
key1: value1,
key2: value2,
key3: value3,
};
- myObject: The name of your object variable.
- { }: Objects are defined using curly braces.
- key: A unique identifier (string or symbol) for each property.
- value: The data associated with a key—can be any data type.
Objects are ideal for representing structured data and modeling real-world entities. You can access or modify properties using either dot notation (object.key) or bracket notation (object["key"]).
Creating an Object
In JavaScript, objects are used to store collections of key-value pairs. Here are a few common ways to create objects:
1. Using Curly Braces (Object Literal)
The most common way to create an object is by using curly braces and defining key-value pairs inside.
const person = {
name: 'Tom',
age: 30,
isStudent: false
};
const person = {
name: 'Tom',
age: 30,
isStudent: false
};
2. Creating an Empty Object
You can start with an empty object and add properties to it later using dot or bracket notation.
const book = {};
book.title = '1984';
book.author = 'George Orwell';
console.log(book); // { title: '1984', author: 'George Orwell' }
const book = {};
book.title = '1984';
book.author = 'George Orwell';
console.log(book); // { title: '1984', author: 'George Orwell' }
3. Using new Object()
You can also use the new Object() constructor to create an object. This approach is less common but still valid.
const car = new Object();
car.make = 'Toyota';
car.model = 'Corolla';
console.log(car); // { make: 'Toyota', model: 'Corolla' }
const car = new Object();
car.make = 'Toyota';
car.model = 'Corolla';
console.log(car); // { make: 'Toyota', model: 'Corolla' }
Accessing Object Properties
In JavaScript, objects store data as key-value pairs. You can access these values using two primary methods: dot notation and bracket notation. Here are the most common ways to access properties in an object:
1. Dot Notation
Dot notation is the most common and concise way to access properties in an object. The key must be a valid identifier (no spaces or special characters).
const user = {
name: "Tom",
age: 30
};
// Accessing properties using dot notation
console.log(user.name); // Output: Tom
console.log(user.age); // Output: 30
const user = {
name: "Tom",
age: 30
};
// Accessing properties using dot notation
console.log(user.name); // Output: Tom
console.log(user.age); // Output: 30
In the example above, we accessed the name and age properties directly using the dot syntax.
2. Bracket Notation
Bracket notation allows you to use strings or variables as keys. It’s useful when keys have special characters, spaces, or are stored in variables.
const user = {
"full name": "Tom Smith",
age: 30
};
console.log(user["full name"]); // Output: Tom Smith
// Using a variable as the key
const key = "age";
console.log(user[key]); // Output: 30
const user = {
"full name": "Tom Smith",
age: 30
};
console.log(user["full name"]); // Output: Tom Smith
// Using a variable as the key
const key = "age";
console.log(user[key]); // Output: 30
In the example above, we used bracket notation to access a key with a space and to dynamically retrieve a property using a variable.
3. Accessing Nested Properties
Objects can contain nested objects. You can access nested properties by chaining dot or bracket notation.
const student = {
name: "Jack",
contact: {
email: "Jack@example.com",
phone: "123-456-7890"
}
};
// Accessing nested properties
console.log(student.contact.email); // Output: Jack@example.com
console.log(student["contact"]["phone"]); // Output: 123-456-7890
const student = {
name: "Jack",
contact: {
email: "Jack@example.com",
phone: "123-456-7890"
}
};
// Accessing nested properties
console.log(student.contact.email); // Output: Jack@example.com
console.log(student["contact"]["phone"]); // Output: 123-456-7890
In the example above, we accessed values inside a nested contact object using both dot and bracket notation.
4. Handling Non-Existent Properties
If you try to access a property that doesn't exist, JavaScript returns undefined instead of throwing an error. You can check for existence before using the value.
const product = {
name: "Laptop",
price: 1200
};
console.log(product.stock); // Output: undefined
// Check before accessing
if (product.stock !== undefined) {
console.log(product.stock);
} else {
console.log("Property does not exist!");
}
const product = {
name: "Laptop",
price: 1200
};
console.log(product.stock); // Output: undefined
// Check before accessing
if (product.stock !== undefined) {
console.log(product.stock);
} else {
console.log("Property does not exist!");
}
In the example above, we tried to access a non-existent stock property and handled it gracefully using a simple condition.
Modifying Object Properties
In JavaScript, objects are mutable, which means you can add, update, or remove properties after the object is created. Here are several common ways to modify object properties:
1. Updating an Existing Property
You can update a property's value using either dot notation or bracket notation.
const user = {
name: "Tom",
age: 30
};
// Updating a property
user.age = 31;
user["name"] = "Alicia";
console.log(user); // Output: { name: 'Alicia', age: 31 }
const user = {
name: "Tom",
age: 30
};
// Updating a property
user.age = 31;
user["name"] = "Alicia";
console.log(user); // Output: { name: 'Alicia', age: 31 }
In the example above, we updated the age and name properties using both notations.
2. Adding a New Property
You can add new properties to an object at any time by assigning a value to a new key.
const book = {
title: "1984",
author: "George Orwell"
};
// Adding a new property
book.year = 1949;
book["genre"] = "Dystopian";
console.log(book); // Output: { title: '1984', author: 'George Orwell', year: 1949, genre: 'Dystopian' }
const book = {
title: "1984",
author: "George Orwell"
};
// Adding a new property
book.year = 1949;
book["genre"] = "Dystopian";
console.log(book); // Output: { title: '1984', author: 'George Orwell', year: 1949, genre: 'Dystopian' }
Here, we added year and genre as new properties to the object.
3. Deleting a Property
You can remove a property from an object using the delete operator.
const car = {
make: "Toyota",
model: "Corolla",
year: 2020
};
// Deleting a property
delete car.year;
console.log(car); // Output: { make: 'Toyota', model: 'Corolla' }
const car = {
make: "Toyota",
model: "Corolla",
year: 2020
};
// Deleting a property
delete car.year;
console.log(car); // Output: { make: 'Toyota', model: 'Corolla' }
In this example, we used delete to remove the year property from the car object.
4. Modifying Nested Properties
You can update nested properties by chaining dot or bracket notation.
const profile = {
username: "johndoe",
contact: {
email: "john@example.com",
phone: "123-456-7890"
}
};
// Updating nested properties
profile.contact.email = "john.doe@example.com";
console.log(profile.contact.email); // Output: john.doe@example.com
const profile = {
username: "johndoe",
contact: {
email: "john@example.com",
phone: "123-456-7890"
}
};
// Updating nested properties
profile.contact.email = "john.doe@example.com";
console.log(profile.contact.email); // Output: john.doe@example.com
We modified the nested email property within the contact object.
5. Replacing the Entire Object
If needed, you can replace the entire object by assigning a new object to the same variable.
let settings = {
theme: "light",
notifications: true
};
// Replacing the whole object
settings = {
theme: "dark",
notifications: false,
layout: "grid"
};
console.log(settings); // Output: { theme: 'dark', notifications: false, layout: 'grid' }
let settings = {
theme: "light",
notifications: true
};
// Replacing the whole object
settings = {
theme: "dark",
notifications: false,
layout: "grid"
};
console.log(settings); // Output: { theme: 'dark', notifications: false, layout: 'grid' }
In this case, we reassigned the settings variable to a completely new object.
Custom Methods & this Keyword in Objects
In JavaScript, objects can have custom methods—functions assigned as property values. These methods can access the object's own data using the this keyword.
1. Defining a Custom Method
A custom method is just a function assigned to a property in an object. You can call it using dot or bracket notation.
// Object with a custom method
const user = {
name: "Tom",
greet: function() {
console.log("Hello!");
}
};
// Calling the method
user.greet(); // Output: Hello!
// Object with a custom method
const user = {
name: "Tom",
greet: function() {
console.log("Hello!");
}
};
// Calling the method
user.greet(); // Output: Hello!
In this example, greet is a method defined on the user object.
2. Using this to Access Object Properties
Inside a method, this refers to the object that owns the method. It's commonly used to access or modify the object's own properties.
// Using 'this' in a method
const user = {
name: "Tom",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
user.greet(); // Output: Hello, my name is Tom
// Using 'this' in a method
const user = {
name: "Tom",
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
user.greet(); // Output: Hello, my name is Tom
Here, this.name refers to the name property of the user object.
3. Shorthand Method Syntax
JavaScript supports a cleaner way to define methods using shorthand syntax introduced in ES6.
// Shorthand method syntax
const user = {
name: "Tom",
greet() {
console.log("Hello, I'm " + this.name);
}
};
user.greet(); // Output: Hello, I'm Tom
// Shorthand method syntax
const user = {
name: "Tom",
greet() {
console.log("Hello, I'm " + this.name);
}
};
user.greet(); // Output: Hello, I'm Tom
This syntax makes the code more concise while keeping the same functionality.
4. Arrow Functions and this
Arrow functions do not bind their own this — they inherit it from the surrounding scope. Therefore, avoid using them for object methods when you need access to the object itself.
// Arrow function does NOT work correctly with 'this' in methods
const user = {
name: "Tom",
greet: () => {
console.log("Hello, I'm " + this.name); // 'this' is not user
}
};
user.greet(); // Output: Hello, I'm undefined
// Arrow function does NOT work correctly with 'this' in methods
const user = {
name: "Tom",
greet: () => {
console.log("Hello, I'm " + this.name); // 'this' is not user
}
};
user.greet(); // Output: Hello, I'm undefined
Use regular functions for methods if you need to access this reliably.
5. Example: Custom Method Modifying Object
Custom methods can also modify the object’s own data using this.
// Method modifying the object
const counter = {
value: 0,
increment() {
this.value += 1;
}
};
counter.increment();
counter.increment();
console.log(counter.value); // Output: 2
// Method modifying the object
const counter = {
value: 0,
increment() {
this.value += 1;
}
};
counter.increment();
counter.increment();
console.log(counter.value); // Output: 2
Here, the increment() method modifies the value property of the object.
Frequently Asked Questions
What is a JavaScript object?
What is a JavaScript object?
A JavaScript object is a collection of key-value pairs used to store related data and functionality.
How do I create an object in JavaScript?
How do I create an object in JavaScript?
You can create an object using object literal syntax, for example: const obj = { key: 'value' }.
What are object methods in JavaScript?
What are object methods in JavaScript?
Object methods are functions that are stored as properties of an object and can be called to perform actions related to that object.
Can JavaScript objects contain other objects?
Can JavaScript objects contain other objects?
Yes, objects can be nested inside other objects, allowing you to model complex data structures.
How do I add or modify properties in a JavaScript object?
How do I add or modify properties in a JavaScript object?
You can add or modify properties using dot notation (obj.key = value) or bracket notation (obj['key'] = value).
What’s Next?
Next, you’ll dive into essential object utility methods in JavaScript. You'll learn how to inspect, control, and protect objects using built-in functions like Object.keys()
, Object.values()
, Object.hasOwnProperty()
, Object.freeze()
, and Object.seal()
.