Objects in JavaScript are non-primitive data types that can store multiple types or collections of data and methods. A variable or a constant can only store one type of data, but an object can store multiple types at once.
We already learnt about Primitive and Non-Primitive data types in our 👉 JavaScript Data Types lesson.
Real World Explanation about JavaScript Objects 🤔
So, why are objects so important in programming? Well, JavaScript is an Object Oriented Programming (OOP) Language, therefore a JavaScript programmer has to learn about objects.
Another big reason why objects are so powerful is because we can use them to represent real-life objects like a bicycle, car, table, computer, house, cat, dog, etc.
Real life objects are anything and everything that we, as humans, can talk about, know of and have experienced it.
As a software developer, your job will be to create solutions to real-world problems, therefore, for that reason, programmers created Objects which can be used to represent things/objects in the real world.
Creating JavaScript Objects 🤯
JavaScript Objects can be created or declared using curly braces { }. The curly braces are also known as object literals.
Syntax
// Here, "dog" is an object having properties: 'name', 'breed', 'age' and 'hasTail'
const dog = {
name: "Jacky",
breed: "German Shepherd",
age: 4,
hasTail: true,
};
Explanation
Objects are represented by one or more key: value pairs separated by commas ,.
Here, the key: value pairs are: name: “Jacky”, breed: “German Shepherd”, age: 4 and hasTail: true, where name, breed, age and hasTail are keys and “Jacky”, “German Shepherd”, 4 and true are values.
As you can see “Jacky” and “German Shepherd” are strings whereas 4 is a number and true is a boolean data type. Thus, objects in JavaScript can store more than one type of data.
Accessing Object Properties
There are two ways to access the properties of an object:
1. Using dot operator 🤓
We can use the dot . operator to access any of the defined properties of an object.
Syntax
Object.propertyName
Example
const dog = {
name: "Jacky",
breed: "German Shepherd",
age: 4,
hasTail: true,
};
// Displays "Jacky"
console.log(dog.name);
// Displays "German Shepherd"
console.log(dog.breed);
// Displays "4"
console.log(dog.age);
// Displays "true"
console.log(dog.hasTail);
Output
Jacky
German Shepherd
4
true
2. Using brackets 😎
We can also use brackets [ ] to access any of the defined properties of an object.
Syntax:
Object['propertyName']
Example
const dog = {
name: "Jacky",
breed: "German Shepherd",
age: 4,
hasTail: true,
};
// Displays "Jacky"
console.log(dog["name"]);
// Displays "German Shepherd"
console.log(dog["breed"]);
// Displays "4"
console.log(dog["age"]);
// Displays "true"
console.log(dog["hasTail"]);
Output
Jacky
German Shepherd
4
true
Difference between dot operator and brackets 🤫
The only difference between using the dot . operator and brackets [ ] is that when we have a property in an object that has spaces, then we cannot use the . operator anymore as it will give errors. Therefore, brackets [ ] come in handy.
Example (Incorrect) ⛔
const laptop = {
name: "Macbook Pro",
"model No": "1234AA",
colorsAvailable: ["Silver", "Rose Gold", "Gray"],
};
// Throws error
console.log(laptop.'model No');
Output
SyntaxError: Unexpected string
Example (Correct) ✅
const laptop = {
name: "Macbook Pro",
"model No": "1234AA",
colorsAvailable: ["Silver", "Rose Gold", "Gray"],
};
console.log(laptop.name);
console.log(laptop.colorsAvailable);
// Displays "1234AA"
console.log(laptop["model No"]);
Output
Macbook Pro
[ 'Silver', 'Rose Gold', 'Gray' ]
1234AA
Updating value of a Property in an Object ✏
We can also update or modify values of already defined properties in an object. We can simply do that by accessing that property using any one of the . operator or [ ] and then using the assignment operator =.
Example
const fruit = {
name: "Apple",
color: "Red",
};
// Displays "Apple"
console.log(fruit.name);
// Update the "name" property of the object "fruit"
fruit.name = "Orange";
// Displays "Orange"
console.log(fruit.name);
// Display the updated object
console.log(fruit);
Output
Apple
Orange
{ name: 'Orange', color: 'Red' }
Add a new Property in an Object 😲
We can also add a completely new property on an already defined object, just by using either one of the . operator or [ ]. But be sure to assign values to the newly added properties.
Example
const house = {
location: "New York, USA",
rooms: 8,
};
console.log(house);
// Adding new properties "floors" and "hasGarage", and also assigning values to them.
house.floors = 4;
house.hasGarage = true;
console.log(house);
Output
{ location: 'New York, USA', rooms: 8 }
{ location: 'New York, USA', rooms: 8, floors: 4, hasGarage: true }
Delete a Property 🗑
We can delete an already defined property on an object with the help of the delete operator.
Example
const friend = {
name: "Johnny Bravo",
age: 16,
hairColor: "Yellow",
};
console.log(friend);
// Deleting the property "hairColor" from the "friend" object
delete friend.hairColor;
console.log(friend);
Output
{ name: 'Johnny Bravo', age: 16, hairColor: 'Yellow' }
{ name: 'Johnny Bravo', age: 16 }
Nested JavaScript Objects 🔗
It is also possible to store objects inside other objects. We can add a property having an object value inside another object.
We can access nested objects’ properties the same way we did with normal objects i.e. by using either dot . operator or brackets [ ].
Example
const friend = {
name: "Steve Jobs",
worksAt: "Apple Inc.",
// Creating a property called "parents" which stores an object having properties "father" and "mother".
parents: {
father: "Paul Jobs",
mother: "Clara Jobs",
},
};
console.log(`Meet my friend ${friend.name}. He works at ${friend.worksAt}`);
// We can access nested objects' properties by using either dot "." operator or brackets "[]".
console.log(`Hi, I'm ${friend.name}. My parents are ${friend.parents.father} and ${friend.parents["mother"]}.`);
Output
Meet my friend Steve Jobs. He works at Apple Inc.
Hi, I'm Steve Jobs. My parents are Paul Jobs and Clara Jobs.
Objects are one of the most, if not, the most important topics to master in JavaScript. The next lessons will help you do exactly that.