On this page
JavaScript Objects
What is an Object?
An object is a collection of properties, and a property is an association between a name (or key) and a value. A value can be a function, in which case the property is known as a method.
Creating an Object
There are multiple ways to create objects in JavaScript:
-
Using an object literal:
let person = { firstName: "John", lastName: "Doe", age: 30, fullName: function() { return this.firstName + " " + this.lastName; } }; console.log(person); // {firstName: "John", lastName: "Doe", age: 30, fullName: ƒ}
-
Using the Object constructor:
let person = new Object(); person.firstName = "John"; person.lastName = "Doe"; person.age = 30; person.fullName = function() { return this.firstName + " " + this.lastName; }; console.log(person); // {firstName: "John", lastName: "Doe", age: 30, fullName: ƒ}
Accessing Object Properties
You can access object properties in two ways:
-
Dot notation:
console.log(person.firstName); // "John" console.log(person.age); // 30
-
Bracket notation:
console.log(person["firstName"]); // "John" console.log(person["age"]); // 30
Adding and Modifying Properties
You can add new properties or modify existing ones using dot or bracket notation:
person.gender = "male";
person["nationality"] = "American";
person.age = 31;
console.log(person);
// {firstName: "John", lastName: "Doe", age: 31, fullName: ƒ, gender: "male", nationality: "American"}
Removing Properties
You can remove properties using the delete operator:
delete person.age;
console.log(person);
// {firstName: "John", lastName: "Doe", fullName: ƒ, gender: "male", nationality: "American"}
Object Methods
Methods are functions stored as object properties:
let person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // "John Doe"
Looping through Object Properties
You can loop through the properties of an object using a for...in
loop:
for (let key in person) {
console.log(key + ": " + person[key]);
}
// Output:
// firstName: John
// lastName: Doe
// fullName: function() { return this.firstName + " " + this.lastName; }
Nested Objects
Objects can also contain other objects:
let person = {
name: "John",
age: 30,
address: {
street: "123 Main St",
city: "New York",
country: "USA"
}
};
console.log(person.address.city); // "New York"
Object.keys(), Object.values(), and Object.entries()
You can use these methods to get the keys, values, and entries of an object:
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
console.log(Object.keys(person)); // ["firstName", "lastName", "age"]
console.log(Object.values(person)); // ["John", "Doe", 30]
console.log(Object.entries(person)); // [["firstName", "John"], ["lastName", "Doe"], ["age", 30]]