An object is one of JavaScript's data types. Objects consist of a collection of key:value pairs. The key in key:value is also known as name. So key:value and name:value both refer to the same thing. For consistency, we'll use key:value in this blog.
The key:value pairs hold properties and methods. Properties hold primitive data types, such as strings, numbers, other objects, and Booleans. Methods are actions that can be performed on the object. Object methods are object properties that contain a function.
Objects are a foundational part of programming in JavaScript. They allow us to group similar properties together into one unit. For example, a todo list application may store its data consisting of tasks and notes in objects.
In this blog, we'll go over:
There are two ways to create an object:
{}
new
keywordUsing object literals, the syntax looks like this when we create an empty object:
const objectLiteral = {}
Using object constructors, the syntax looks like this when we create an empty object:
const objectConstructor = new Object()
Let's take a look at creating an object with some more stuff inside the object.
Here, we create the city
object using the object literal approach:
// Create city object using an object literal
let city = {
name: 'San Francisco',
landmarks: ['Golden Gate Bridge', 'Coit Tower', 'Lombard Street'],
fog: 'Karl',
greet: function() {
console.log(`Welcome to ${this.name}`)
},
}
console.log(city)
// {name: 'San Francisco', landmarks: Array(3), fog: 'Karl', greet: ƒ}
Here, we create the city
object using the object constructor approach:
// Create object constructor function, which will serve as our blueprint. Yes, City is spelled with a capital C.
function City(name, landmarks, fog, greet) {
this.name = name
this.landmarks = landmarks
this.fog = fog
this.greet = greet
}
// Create object, city, with properties and methods from the City blueprint.
let city = new City(
'San Francisco',
['Golden Gate Bridge', 'Coit Tower', 'Lombard Street'],
'Karl',
function() {
console.log(`Welcome to ${this.name}`)
}
)
console.log(city)
// City {name: "San Francisco", landmarks: Array(3), fog: "Karl", greet: ƒ}
In both examples above, we created an object, city
.
city
has three properties: name
, landmarks
, fog
.
city
has one method: greet
, which is a function. In the greet
function, this
refers to the current object, city
. So ${this.name}
refers to 'San Francisco'
. The backticks, dollar sign, and curly braces ${}
are template literals in JavaScript.
Using object literals, {}
, is the more common and preferred method of creating an object because it's quicker to write due to the shorter syntax.
Object properties are the characteristics of an object. Properties can contain any data type.
A method is an object property that has a function as its value. A method is a task that an object can perform.
Let's revisit our earlier example object, city
:
name
, landmarks
, and fog
from the city
are properties of the object, city
.greet
is a method of the object, city
.// Create city object
let city = {
// Object properties:
name: 'San Francisco',
landmarks: ['Golden Gate Bridge', 'Coit Tower', 'Lombard Street'],
fog: 'Karl',
// Object method:
greet: function() {
console.log(`Welcome to ${this.name}`)
},
}
There are two ways to access object properties:
objectName.property
objectName[property]
Again, let's revisit our object, city
.
let city = {
name: 'San Francisco',
landmarks: ['Golden Gate Bridge', 'Coit Tower', 'Lombard Street'],
fog: 'Karl',
greet: function() {
console.log(`Welcome to ${this.name}`)
},
}
Below, we use dot notation to access the name
property from the object, city
. We also use bracket notation to access the landmarks
property.
// Use dotation to access name property
city.name
// "San Francisco"
// Use bracket notation to access landmarks property
city['landmarks']
// ["Golden Gate Bridge", "Coit Tower", "Lombard Street"],
We use the same syntax to access an object's method. Here we call the greet
method from city
using dot notation and bracket notation. Dot notation is preferred.
// Call the greet function using dot notation
city.greet()
// Welcome to San Francisco
// Call the greet function using bracket notation
city['greet']()
// Welcome to San Francisco
JavaScript objects are mutable (can be changed). We can assign new values with the assignment operator, =
.
In this example, we add a new property, nickname
to city
. When we print city
, we see the new property added.
// Add nickname property using the assignment operator, =
city.nickname = 'The City'
console.log(city)
// {name: "San Francisco", landmarks: Array(3), fog: "Karl", nickname: "The City", greet: ƒ}
To modify an object property, we use dot or bracket notation along with the =
operator to assign a new value.
In this example, we first use dot notation to change the value of nickname
to 'San Fran'
. When we print out city
, we confirm that the nickname property has indeed been updated. But, no one actually calls San Francisco, San Fran. So let's use bracket notation to update nickname
to 'SF'
.
// Update nickname to San Fran
city.nickname = 'San Fran'
console.log(city)
// {name: "San Francisco", landmarks: Array(3), fog: "Karl", nickname: "San Fran", greet: ƒ, …}
// Update nickname to SF
city['nickname'] = 'SF'
console.log(city)
// {name: "San Francisco", landmarks: Array(3), fog: "Karl", nickname: "SF", greet: ƒ, …}
To remove an object property, we use the delete
keyword.
fog
isn't actually a good property to have on the city
object because not all cities have fog. This means having the fog
property is not good for code reusability. Let's make the city
object more general by removing the fog
property with the delete
keyword. true
will be printed when fog
is deleted. Then let's print city
to see that fog
is no longer a property of city
.
// Delete the fog property
delete city.fog
// Output:
// true
console.log(city)
// {name: "San Francisco", landmarks: Array(3), nickname: "The City", greet: ƒ}
The for...in
loop is used to iterate over properties of an object.
We can use the for...in
loop to traverse over the object and print both the key and value. In this example, we loop through city
and print out its key and value. key
refers to the key, and city[key]
refers to the value.
// Loop over city and print the keys and values
for (let key in city) {
console.log(`${key}: ${city[key]}`)
}
// Output:
// name: San Francisco
// landmarks: Golden Gate Bridge,Coit Tower,Lombard Street
// nickname: SF
// greet: function () {
// console.log(`Welcome to ${this.name}`);
// }
Objects are a fundamental part of organizing code and functionality in JavaScript.
Here's a recap of what we learned in this blog,
new
keyword.
or bracket notation []
=
delete
keywordfor...in
loopFor further reading, check out these articles: