Javascript is an object-based programming language in which except for few primitive types everything is an object.
Objects in javascript are not class based like in other programming languages. They are quite independent and they don’t have any restrictions on the names of the new properties and methods or on the values.
What is an object in javascript?.
Basically, Objects in javascript are a box of properties which are mutable, where properties are represented by key-value pair. Key can be any string including the empty string and value can be of any type available in javascript except it cannot be undefined
that means it is mandatory to assign a value
to the key
.
They are very useful in storing and organizing the data and as objects can have another object, they are very handy in representing the tree or graph structures.
Except for numbers
, strings
, booleans
, null
and undefined
all other things are objects in javascript. While numbers
, strings
, booleans
are object-like as they have methods, but they are immutable.
With the introduction of ES6, there are various new capabilities added to the Objects.
list of objects in javascript
- Dates
- Regular Expressions
- Maths
- Arrays
- Functions
- Objects
- Booleans (When called as constructor with
new
keyword.) - Strings (When called as constructor with
new
keyword.) - Numbers (When called as constructor with
new
keyword.)
Declaring Objects in Javascript
There are different ways through which we can create objects in javascript.
Using object literals
The most simplest and prominent method to declare objects in javascript is by using { }
braces.
let obj = {}; obj.name = 'Prashant'; obj["age"] = 24; let obj2 = { "name": 'Prashant', age: 24 };
As the keys of the objects can be any string including the empty string we can omit the quotes around the property names while declaring in object literals if the string does not contain any spaces.
You can also nest the objects within the objects.
let obj = { name: "Prashant", age: 24, details: { hobbies: ["Cycling", "Writing", "Teaching"], Gender: "Male", } }
We can also declare functions which are called methods
inside the objects.
let obj = { name: 'Prashant', getName: function() { return this.name; } } console.log(obj.getName()); //"Prashant"
You can also check out the new syntax of declaring the methods inside the object.
By creating instance of the object using new
keyword.
let obj = new Object(); obj.name = "Prashant"; obj.age = 24; obj.getDetails = function(){ return `${this.name} is ${this.age} years old`; }; console.log(obj.getDetails()); //"Prashant is 24 years old"
By creating a constructor
In javascript, we can create a function which can be used as a constructor to create new objects.
function Obj(name, age){ //Properties this.name = name; this.age = age; //Methods this.getDetails = function(){ return `${this.name} is ${this.age} years old`; } } let person = new Obj("Prashant", 24); console.log(person.getDetails()); //"Prashant is 24 years old" let person2 = new Obj("Sachin", 23); console.log(person2.getDetails()); //"Sachin is 23 years old"
This is very useful as it allows you to mimic the class-based objects but the properties and methods cannot be made private.
Retrieving data from objects
Values from objects can be retrieved using two different techniques.
Using dot .
notation
We can use the period or .
to retrieve the value of properties or call the methods if the name of the properties names does not contains any space.
let obj = { name: "Prashant", "what is this": "Example", "my age": 25 }; obj.name; //"Prashant" obj.what is this //Uncaught SyntaxError: Unexpected identifier
We get an error when trying to access the property names which has spaces.
Using []
to access the values
In cases where you are not sure about the properties name whether it contains white space or not you can use []
notations.
let obj = { name: "Prashant", "what is this": "Example", "my age": 25 }; obj["name"]; //"Prashant" obj["what is this"]; //"Example" obj["my age"]; //25
Both methods may be giving the required result but there is a little difference in the way they work.
The word after the period or .
is interpreted as object literal while the world inside the []
are evaluated and then the value assigned to evaluated word is returned. Let us see the below example for better understanding.
let obj = { 1: "one", 2: "two", 3: "three" }; for(let i = 1; i <= 3; i++){ console.log(obj.i); } //undefined //undefined //undefined for(let i = 1; i <= 3; i++){ console.log(obj[i]); } //"one" //"two" //"three"
In the first loop when we are using period or .
to retrieve the value it is returning undefined
because it is treating i
as a property name and there is no key with i
name inside the object.
On the other hand in the second loop, the value of i
is evaluated inside the obj[i]
and it becomes obj[1]
so it returns one
.
Handling the non existent property
Retrieving the property which does not exist inside the obj will return undefined
.
let obj = { first_name: "Prashant" }; obj.first_name; //"Prashant" obj.last_name; //undefined
We can use the ||
operator to fill in the default value whenever property does not exists.
let lastName = obj.last_name || "Yadav"; //"Yadav"
Accessing the property of nonexistence properties will result in an error, it is better to use &&
operator to restrict the error.
obj.last_name; //undefined obj.last_name.intial //Uncaught TypeError: Cannot read property 'intial' of undefined obj.last_name && obj.last_name.intial //undefined
&&
will evaluate the right hand side expression only if the left hand side expression is true
.
Updating the object values
We can update the values of the object by assigning the new values to it. If the property does not already exists then it will add a new one.
let obj = { name: "Prashant" } obj.name = "Sachin"; obj.name; //"Sachin" obj.age = 24; obj.age; //24 obj["gender"] = "Male"; obj["gender"]; //"Male"
While copying the value from another object always remember objects are always passed around as a reference they are never actually copied.
let obj = {}; let person = obj; person.name = "Prashant"; let person2 = obj.name; person2; //"Prashant"
In the above example if you see we have assigned value to the person.name
but when we are accessing obj.name
we are getting same value because we are referencing to the same object.
//Referencing to the same object let a = b = c = {}; //Referencing to the different objects let a = {}, b = {}, c = {};
Copying an object in javascript
Shallow copy
If we want to do a shallow copy of an object then we can use Object.assign(To, From)
method which copies one object to other.
let obj = { name: "Prashant", age: 24, details: { gender: "Male" } }; let copy = Object.assign({}, obj); copy.name; //"Prashant" copy.age //24 copy.details.gender; //"Male" //Update the gender obj.details.gender = "Female"; copy.details.gender; //"Female"
As you can see we have updated the value of obj.details.gender = "Female";
and it is reflected to the copied object copy.details.gender;
.
In shallow copy, the nested objects are still passed as a reference to the new object.
Deep copy
We can use JSON.parse()
and JSON.stringify()
together to create a deep copy of an object.
let obj = { name: "Prashant", age: 24 }; let copy = JSON.parse(JSON.stringify(obj)); copy.name; //"Prashant" copy.age //24
Extending objects with prototype
Every object in javascript is linked to a prototype object from which it can inherit properties and methods. Prototype object comes standard with javascript and is available with every object that is created with object literals.
let obj = {}; obj.name = "Prashant"; obj.age = 24; obj.prototype.getDetails = function(){return `${this.name} is ${this.age} years old`}; console.log(obj.getDetails()); //"Prashant is 24 years old"
While accessing the value from the object if the property is not present then it will look into its prototype object and if it is not present here then it will look into its prototype until it bottoms out.
If the property is not present in prototype linkage then it will return undefined
. This process of looking into the prototype chain is called Delegation.
Deleting object properties
We can use the delete
operator to remove the property from the object. If the property is not present then it will simply ignore it.
let obj = {}; obj.name = "Prashant"; obj.age = 24; //Add properties and Methods inside the prototype. obj.prototype.age = 23; obj.prototype.getDetails = function(){return `${this.name} is ${this.age} years old`}; console.log(obj.getDetails()); //"Prashant is 24 years old" //Remove age delete obj.age; console.log(obj.getDetails()); //"Prashant is 23 years old"
It will only delete the property from the given object, It will not remove it from its prototype link. So if the property is present in the prototype then it will access that one.
Checking if property or method exist in object
Using hasOwnProperty()
We can use hasOwnProperty()
to check if object has a given property or method. It will not check for the properties present in the prototype chain.
let obj = { name: "Prashant", age: 24, getDetails: function(){ return `${this.name} is ${this.age} years old`; } }; //Adding property to prototype obj.prototype.gender = "Male"; console.log(obj.hasOwnProperty("name")); //true console.log(obj.hasOwnProperty("age")); //true console.log(obj.hasOwnProperty("getDetails")); //true console.log(obj.hasOwnProperty("gender")); //false
Using in
operator
We can use in
operator to check if a given property exist or not. It will look for the property in the prototype chain also.
let obj = { name: "Prashant", age: 24, getDetails: function(){ return `${this.name} is ${this.age} years old`; } }; //Adding property to prototype obj.prototype.gender = "Male"; console.log("name" in obj); //true console.log("age" in obj); //true console.log("getDetails" in obj); //true console.log("gender" in obj); //true
Enumerating the objects in javascript.
Using for...in
loop
We can use the for...in
loop to iterate through each property of the given object.
let obj = { name: "Prashant", age: 24, getDetails: function(){ return `${this.name} is ${this.age} years old`; } }; //Adding property to prototype obj.prototype.gender = "Male"; for(let key in obj){ console.log(obj[key]); } //"Prashant" //24 /* function () { return `${this.name} is ${this.age} years old`; } */ //"Male"
It iterates through all the properties, even the one in prototye chain. We can restrict to enumerate through the properties in the current scope only using hasOwnProperty()
.
for(let key in obj){ if(obj.hasOwnProperty(key)){ console.log(obj[key]); } } //"Prashant" //24 /* function () { return `${this.name} is ${this.age} years old`; } */
As we can see the source code for the methods are getting printed because we are accessing them not evaluating them with ()
. So we can restrict them as well by checking their type.
for(let key in obj){ if(obj.hasOwnProperty(key) && typeof obj[key] !== 'function'){ console.log(obj[key]); } } //"Prashant" //24
Using Object.Keys.
Object.Keys(obj)
takes an object as an input and returns the array of keys as a output. It does not return keys from the prototype chain so we can use this safely.
console.log(Object.keys(obj)); //["name", "age", "getDetails"]
We can use this array of keys to iterate through each property of the object.
for...of
loop
//For of loop for(let key of Object.keys(obj)){ if(typeof obj[key] !== 'function'){ console.log(obj[key]); } } //"Prashant" //24
forEach
loop
//For each loop Object.keys(obj).forEach((key) => { if(typeof obj[key] !== 'function'){ console.log(obj[key]); } }); //"Prashant" //24
We can clearly see that the object is the heart of the javascript. That is why it is continuously evolving. You can check out the new features that are introduced in ES6.
Here is the complete list of object methods.
Shiv says:
For deep copy we can add structuredClone also.
virincihi says:
Your content is truly exceptional, and there’s no doubt about it. I’ve been visiting this website for the past year, and I was unaware of the incredibly high-quality content you offer. The only reason it hasn’t gained popularity is due to its lacking user interface (UI), user experience (UX), and overall lack of user-friendliness.
However, I firmly believe that you will address these issues and make the necessary improvements.
Thanks for all that you have contributed
Prashant Yadav says:
Will definitely address it