Definition
An object is an entity with a set of properties(primitive values and objects) and behaviors(methods).
The properties have a key-value pair relationship, where the keys correspond to a specific value. It is similar to an unordered map in C++.
Creating Object in JS
To create an object in JavaScript, we can use one of the following ways:
- Using an object literal
- Using the keyword ‘new’
- Using constructor
Let us have a look at them one by one:
Object literal
Object literal refers to a comma-separated list of key-value pairs. Using it we can define and create objects at the same time.
In this example we created a Student object with name,age and id properties.
let Student = {
name: 'Michael',
age: 15,
id: 1001
}
You can also try this code with Online Javascript Compiler
Run Code
‘new’ keyword
Here a new object student is created using a new keyword and then we are adding name and age property to the student.
const student = new Object();
student.name = 'Michael';
student.age = 15;
You can also try this code with Online Javascript Compiler
Run Code
Constructor
function Student(name, age, id) {
this.name = name;
this.age = age;
this.id = id;
}
const student1 = new Student('John', 14, 1201);
const student2 = new Student('Michael', 15, 1001);
console.log(student1);
console.log(student2);
You can also try this code with Online Javascript Compiler
Run Code
- The function Student(){} is the object constructor function. We can create objects of the same type by calling that function along with a new keyword.
- Here student1 and student2 are two Student objects, with different names, ages, and ids.
Output:
Student { name: 'John', age: 14, id: 1201 }
Student { name: 'Michael', age: 15, id: 1001 }
Let us dig a little deeper and see how to access the object we just created.
Here we are creating a Student object and viewing the entire object by using console.log.
let Student = {
name: 'Michael',
age: 15,
id: 1001,
}
console.log(Student);
You can also try this code with Online Javascript Compiler
Run Code
Output:
{ name: 'Michael', age: 15, id: 1001 }
NOTE:
We can also add properties for our object outside the curly brackets,
let Student = {
name: 'Michael',
age: 15,
id: 1001,
}
Student.email = 'abc@xyz.com';
console.log(Student);
You can also try this code with Online Javascript Compiler
Run Code
Output:
{ name: 'Michael', age: 15, id: 1001, email: 'abc@xyz.com' }
But what if we want to see only the name of the student and not the other details?
To access a specific property of an object, we can use,
- dot(.) operator
- square([ ]) brackets
Accessing through Dot Operator
let Student = {
name: 'Michael',
age: 15,
id: 1001,
}
console.log(Student.name);
You can also try this code with Online Javascript Compiler
Run Code
Output:
Michael
Accessing through Square brackets
let Student = {
name: 'Michael',
age: 15,
id: 1001,
}
console.log(Student['name']);
You can also try this code with Online Javascript Compiler
Run Code
Output:
Michael
But which method should you use to access specific properties of objects?
The simple answer is, you can use the dot operator as it is much more convenient than using square brackets. But there are some instances in which you have no choice other than to use square brackets. In these particular cases, using the dot operator will cause your code to throw an error.
If the name of the key is a number and not a string:
let Student = {
name: 'Michael',
age: 15,
id: 1001,
20: 'twenty',
}
console.log(Student['20']);
You can also try this code with Online Javascript Compiler
Run Code
Output:
twenty
Now if we try to do the same thing utilising the dot operator, the program will throw an error.
console.log(Student.20);
You can also try this code with Online Javascript Compiler
Run Code
Output:
console.log(Student.20);
^^^^^^^
SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
console.log(Student.20);
^^^^^^^
If the name of the key has space-separated strings:
let Student = {
name: 'Michael',
age: 15,
id: 1001,
20: 'twenty',
'full name': 'Michael Doe'
}
console.log(Student['full name']);
You can also try this code with Online Javascript Compiler
Run Code
Output:
Michael Doe
NOTE: It is not a good practice to use variable names which have spaces.
When the key name comes from a variable:
let Student = {
name: 'Michael',
age: 15,
id: 1001,
20: 'twenty',
'full name': 'Michael Doe'
}
var x = 'name';
console.log(Student[x]);
You can also try this code with Online Javascript Compiler
Run Code
Output:
Michael
If you try to use the dot operator, the output comes out to be undefined
console.log(student.x);
You can also try this code with Online Javascript Compiler
Run Code
Output:
undefined
NOTE: If you try to access a property which is not defined inside the object, the output shows ‘undefined’.
let student = {
name: 'Michael',
age: 15,
id: 1001,
}
console.log(student.gender);
You can also try this code with Online Javascript Compiler
Run Code
Output:
undefined
Existence of a property
To check if a property exists inside an object or not, in operator is used.
Syntax: property in object
If the property exists the operator returns true, otherwise false.
let Student = {
name: 'Michael',
age: 15,
id: 1001,
20: 'twenty',
'full name': 'Michael Doe'
}
console.log('gender' in Student);
console.log('age' in Student);
You can also try this code with Online Javascript Compiler
Run Code
Output:
false
true
Now that we have looked upon the basics of Object in JS, let us now dig a little deeper inside its methods:
Methods
We can also have Methods inside Objects in JS. Method is an Object property, which contains a function definition. Therefore, Methods are used to add functionality to Objects.
In the example below, Student is an Object that has a Method speak() .
To invoke a function from an Object we use the following syntax,
Syntax:
object_name.function_name();
let Student = {
name: "Michael",
age: 15,
id: 1001,
20: "twenty",
"full name": "Michael Doe",
speak: function () {
console.log("Hi! I am " + this.name + "and my student id is " + this.id);
},
study: function () {
console.log("I am currently studying!");
},
play: function () {
console.log("I am currently playing!");
},
};
Student.speak();
Student.study();
Student.play();
You can also try this code with Online Javascript Compiler
Run Code
Output:
Hi! I am Michaeland my student id is 1001
I am currently studying!
I am currently playing!
To invoke the speak function of Student we used Student.speak();
Similarly, for study() and play() functions were invoked using
- Student.study();
- Student.play();
ES6 allows us to write a short description of function,
Instead of this,
speak: function () {
console.log("Hi! I am " + this.name + "and my student id is " + this.id);
}
You can also try this code with Online Javascript Compiler
Run Code
We can write this,
speak() {
console.log("Hi! I am " + this.name + "and my student id is " + this.id);
}
You can also try this code with Online Javascript Compiler
Run Code
Like properties, we can also add methods of the object outside the object,
let Student = {
name: 'Michael',
age: 15,
id: 1001,
20: 'twenty',
'full name': 'Michael Doe',
}
Student.speak =
function () {
console.log(`Hi! I am ${this.name} and my student id is ${this.id}`);
}
Student.speak();
You can also try this code with Online Javascript Compiler
Run Code
‘this’ keyword
The ‘this’ keyword inside the method speak refers to the owner object of the method. In our case,
- this.name refers to the ‘name’ of the object ‘student’
- this.id refers to the ‘id’ of the ‘student’
NOTE: this.full name will throw an error, to refer to the ‘full name’ of the student, we have to use the square brackets again.
Student.speak =
function () {
console.log(`Hi! I am ${this["full name"]} and my student id is ${this.id}`);
}
Student.speak();
You can also try this code with Online Javascript Compiler
Run Code
Output:
Hi! I am Michael Doe and my student id is 1001
Removing property of an Object
To delete a specific property of an object, we use the ‘delete’ operator:
let Student = {
name: 'Michael',
age: 15,
id: 1001,
}
delete Student.age;
console.log(Student);
You can also try this code with Online Javascript Compiler
Run Code
Output:
{ name: 'Michael', id: 1001 }
Object inside object
Yes, we can create objects inside an object in JS. Let us see how,
Here within the Student object, we have a nested object called ‘marks’.
let Student = {
name: 'Michael',
age: 15,
id: 1001,
marks: {
English: 89,
Mathematics: 99,
Physics: 76,
Chemistry: 90
}
}
console.log(Student.marks);
You can also try this code with Online Javascript Compiler
Run Code
Output:
{ English: 89, Mathematics: 99, Physics: 76, Chemistry: 90 }
This shows all the properties of marks object, but if we only want to see the marks of Chemistry, we can do so by using the dot operator like this
console.log(Student.marks.Chemistry);
You can also try this code with Online Javascript Compiler
Run Code
Output:
90
How to iterate over Objects in JS?
To iterate over properties of an objects we can use for/in loop:
Syntax: for (key in object)
let Student = {
name: 'Michael',
age: 15,
id: 1001
}
for (key in Student) {
console.log(`Student.${key} : ${Student[key]}`);
}
You can also try this code with Online Javascript Compiler
Run Code
Output:
Student.name : Michael
Student.age : 15
Student.id : 1001
For better understanding, you can practice on an online Javascript compiler.
Must Read Fibonacci Series in JavaScript
Frequently Asked Questions
Q1. What is an Object in JS?
Ans: An object is an entity with a set of properties(primitive values and objects) and behaviors(methods).
Q2. Is an object a primitive data type?
Ans: No, an object is a non-primitive data type.
Q3. What can be used to remove specific properties from an object?
Ans: We can use the ‘delete’ operator to remove specific properties.
Q4. What are the different ways in which we can create an object?
Ans: We can use an object literal, ‘new’ keyword, and constructor to create a new object.
Key Takeaways
In this article, we learned about Objects in JS - a fundamental topic that you will need to understand before you dive deeper into JS. We learned about the various ways by which we can create objects. We also saw how to add methods, remove specific properties from objects, and how to iterate over each property in an object.
We hope you got to learn a lot about Objects in JS. Happy Learning Ninja!