Object in JavaScript
Objects are used widely in JavaScript as we can store different types of data at one place and we can access them efficiently using objects
What is an Object?
An object is a non-primitive data type in JavaScript, We use objects to store a collection of data irrespective of their data type (number, string, boolean etc).
Each value stored in an object has a key associated with it so we can say it holds different key-value pairs in it. The key helps us to access a particular value from an object.
const obj = {};
In the above example, we declared a variable const obj
and we assigned them a pair of curly brackets {}
. This depicts that we have created a new object obj
which for now has no key-value pair inside it (empty object).
Syntax:
Let's see the structure of an object with the help of an example,
In the above example,
name, age, country
are known as thekeys
of the objectobj.
"Abhay", 23, "India"
are known as thevalues
of the objectobj
.The key
name
has the value"Abhay"
and this one key-value pair is known as theproperty
of the objectobj
. Similarly, keyage
with value23
is another property of the objectobj
.console.log(obj)
returns the whole objectobj
with all its properties.The key is also known as the property name of an object.
Note:
The key of an object is usually of string
data type but if in case any other data type value is given to the key (other than a string
), then it will be converted to string
automatically.
const obj = {
1: "orange",
true: "pineapple",
let: "apple",
};
console.log(obj["1"]); //Output: orange
console.log(obj["true"]); //Output: pineapple
console.log(obj["let"]); //Output: apple
console.log(Object.keys(obj));
//Output: ['1', 'true', 'let']
// Here data type of the keys are all string
console.log(obj);
//Output: {1: 'orange', true: 'pineapple', let: 'apple'}
console.log(obj.1); //Output: syntax error
Creating a number key, boolean key, or reserved word key in an object is possible because all the keys with different data types are eventually converted into a string
data type.
When we access all the keys of the object obj
using Object.keys(obj)
, we can see that we get an array of keys with all keys being converted to string
data type.
In the case of Dot notation .
we get a syntax error because it considers (console.log(obj.1)
) 1
to be of number
data type.
Accessing Properties of an Object:
The properties inside an object can be accessed outside the object using one of the following ways:
Dot notation
.
Bracket notation
[]
We will discuss both ways in brief one by one,
Dot notation .
:
Lets us understand with an example,
const userInfo = {
name: "John",
id: 1234,
color: "Blue",
};
console.log(userInfo.name); //Output: John
console.log(userInfo.id); //Output: 1234
console.log(userInfo.color); //Output: Blue
In the above example,
In
console.log(userInfo.name)
we are trying to get the value of the keyname
from the objectuserInfo
.Similarly, in
console.log(userInfo.id)
we are trying to get the value of the keyid
from the objectuserInfo
.Similarly, in
console.log(userInfo.color)
we are trying to get the value of the keycolor
from the objectuserInfo
.
Adding a new key using Dot notation .
:
We can also add a new key to an object using Dot notation .
, let us see with an example,
const objNum = {
a:1,
b:2,
c:3,
};
console.log(objNum); //Output: {a:1, b:2, c:3}
objNum.d = "four";
console.log(objNum);//Output: {a:1, b:2, c:3 , d:'four'}
In this way, we can add a new key to an object using Dot notation .
.
Bracket notation []
:
Adding a new key with the help of Bracket notation []
, Let's see with an example,
const objNum = {
a:1,
b:2,
c:3,
};
console.log(objNum); //Output: {a:1, b:2, c:3}
objNum["d"] = 4;
console.log(objNum); //Output: {a:1, b:2, c:3, d:4}
For adding a property in the above example, we gave the key name inside the square bracket objNum["d"] = 4
and assigned that key a value equal to 4
.
Dot notation .
vs Bracket notation []
:
Bracket notation []
and Dot notation.
both work the same way but there are some minor differences which we will discuss now.
Generally, we use Dot notation .
to access the value of a key from an object or when we want to add a new key in an object, but it has some limitations.
Limitations of Dot notation .
:
Case1: We cannot access the value of a variable while adding or accessing a key from an object:
Suppose we want to use the value of a variable as the name of the key which we want to add to the object,
To understand this better let's see an example:
const carName = "Jeep";
const autoMobile = {}; // we have an empty object
autoMobile.carName = "SUV";
console.log(autoMobile);
//Output: {carName: "SUV"}
In the above example, we tried to set the value of the variable carName
(which is Jeep
) as the name of the key in the object autoMobile
while assigning it a value "SUV"
but it took carName
as the name of the key. So instead of taking the value of the variable carName
, Dot notation .
is considering the variable itself as the key name for the value "SUV"
.
Similarly, we cannot access the value of a variable while accessing it as a key from the object.
const carName = "Jeep";
const autoMobile = {
Jeep: "SUV",
};
const result = autoMobile.carName;
console.log(result);
//Output: undefined
In the above example, we get undefined
because autoMobile.carName
here Dot notation .
is considering the variable name carName
as the key, not its value ("Jeep"
). As there does not exist any key with a name carName
inside the object autoMobile
, it returns undefined
on accessing the variable result
.
So in this case we use Bracket notation []
to access the value of a variable as the key name or property name to access the key or add it to the object. Let's see an example,
const carName = "Jeep";
const keyName = "color";
const autoMobile = {
color: "blue",
};
autoMobile[carName] = "SUV";
// Instead of carName it is taking the value of carName,
// autoMobile["Jeep"] = "SUV"
console.log(autoMobile[keyName]);//It takes the value of keyName , console.log(autoMobile["color"])
//Output: blue
console.log(autoMobile);
//Output: {color: 'blue', Jeep: 'SUV'}
Case 2: Cannot add multi-word key name with Dot notation .
:
Suppose we want to add a key to an object and the key name which we are adding has more than one word in it.
Let's see with an example,
const userInfo = {
name: "Abhay",
};
userInfo.contact number = 8856337725; // "contact number" is a multi-word key
console.log(userInfo); //Output: Syntax error
In the above example, we can see that we cannot multi-word key names using Dot notation .
. It will give a syntax error in that line itself where we tried to add userInfo.contact number = 8856337725
. So in this case we can use Bracket notation []
.
Let's try to do the above example with Bracket notation []
,
const userInfo = {
name: "Abhay",
};
userInfo["contact number"] = 8856337725;
console.log(userInfo);
//Output: {name: 'Abhay', contact number: 8856337725}
In the case of Bracket notation []
, we can also apply some conditions to the key of an object using the ternary operator ?
.
Some cases in Bracket notation []
:
Case 1: Applying condition on a particular key with help of a ternary operator ?
:
const obj = {
name: "Abhay",
color: "Blue",
subject: "Maths",
id: 110,
};
const result = obj[(obj["id"]>100)?"color":"subject"];
console.log(result);
//Output: Blue
In the above example, we are using ternary operator ?
inside the brackets []
where we are checking whether the key id
of object obj
has a value greater than 100
if true
then ternary operator ?
will return "color"
so it will look like this const result = obj["color"]
and if false
then ternary operator ?
returns "subject"
and it will look like this const result = obj["subject"]
.
Case2: Accessing particular values from an object based on a condition and pushing it into a new array:
const newArray = []; //empty array
const obj = {
name: "Abhay",
color: "Blue",
subject: "Maths",
id: 110,
};
newArray.push(obj[(obj["id"]>100)?"color":"subject"]);
console.log(newArray);
//Output: ['Blue']
In the above example,
We created an empty array newArray
and in statement newArray.push(obj[(obj["id"]>100)?"color":"subject"])
inside the push
method we are applying ternary operator ?
inside the object obj
. In condition obj[(obj["id"]>100)?"color":"subject"]
if the key id
in object obj
is greater than 100
then it will return "color"
and so it will look like newArray.push(obj["color"])
or if the id
value is less than 100
then in that case it will return "subject"
and so it will look like newArray.push(obj["subject"])
.
Destructuring with object:
Destructuring helps us to unpack the values from an object and store it in a variable. To get more clarity on how destructuring works let's see some examples,
const userInfo = {
name: "Abhay",
id: 1234,
color: "blue",
};
const name = userInfo.name;
const id = userInfo.id;
const color = userInfo.color;
console.log(name); //Output: Abhay
console.log(id); //Output: 1234
console.log(color); //Output: blue
In the above example, we declared a variable name
and assigned it a value const name = userInfo.name
here we accessed the value of the key name
from the object userInfo
. Similarly, we did this for other values also inside the object userInfo
.
Now let's do the above example using Destructuring,
const userInfo = {
name:"Abhay",
id: 1234,
color:"blue",
};
const {name,id,color} = userInfo;
//This destructuring is similar to:
//const name = userInfo.name;
//const id = userInfo.id;
//const color = userInfo.color;
console.log(name); //Output: Abhay
console.log(id); //Output: 1234
console.log(color); //Output: blue
See how in one line we declared variables name,id,color
and assigned them the values of the respective keys of the object userInfo
.
Note:
But one thing to note here is that the variable name should be the same as the name of the key whose value we are trying to assign to that variable.
const userInfo = {
name: "Abhay",
id: 1234,
color: "blue",
};
const {nam,i,colr} = userInfo;
//The above statement is similar to:
//const nam = userInfo.nam; but nam key is not present in object userInfo thats why it returns undefined
// Similarly, in case of variable i and colr
//const i = userInfo.i;
//const colr = userInfo.colr;
console.log(nam); //Output: undefined
console.log(i); //Output: undefined
console.log(colr); //Output: undefined
So in the above example, we tried to destructure the values of the object userInfo
but for the variable names nam,i,colr
there does not exist keys with the same names in the object userInfo
so it returns undefined
when we try to access the variables.
Accessing nested objects in an object with destructuring:
Let's see an example,
const userInfo = {
name: "Abhay",
id: 1234,
colors: {
a: "blue",
b: "pink",
},
};
const a = userInfo.colors.a;
const b = userInfo.colors.b;
console.log(a); //Output: blue
console.log(b); //Output: pink
In the above example, userInfo.colors.a
statement is firstly accessing the key colors
from the object userInfo
and then we are doing colors.a
further to access the value of the key a
from the object in colors
.
Now let's do the same example with Destructuring,
const userInfo = {
name: "Abhay",
id: 1234,
colors:{
a: "blue",
b: "pink",
},
};
const {name,colors:{a,b}} = userInfo;
//The above statement is similar to,
// const name = userInfo.name;
// const a = userInfo.colors.a;
// const b = userInfo.colors.b;
console.log(name); //Output: Abhay
console.log(a); //Output: blue
console.log(b); //Output: pink
In the above example, const {name,colors:{a,b}}
the outer curley brackets {}
are for the object userInfo
and inside that we have key colors
which have an object as its value and to access the keys a
and b
of that object we have to specify the curly brackets {}
as colors:{a,b}
.
Iterating through an object:
We use for in loop to iterate through the keys of an object. Let's see with an example,
const userInfo = {
name: "Abhay",
id: 1234,
colors: "blue"
};
for(let i in userInfo){
console.log(i);
};
//Output:
// name
// id
// colors
In the above example, we can see that by using for in loop for object userInfo
it is iterating over the keys of the object userInfo
with variable i
defined inside the for in loop.
We can also access the values of the key with the help of for in loop. Let's see with an example,
const userInfo = {
name: "Abhay",
id: 1234,
colors: "blue"
};
for(let i in userInfo){
console.log(i + userInfo.i);
};
//Output:
// name undefined
// id undefined
// colors undefined
Why do we get undefined while trying to access the values using for in loop in the above example?
As variable i
is iterating over the keys of the object userInfo
and for the first iteration of the loop the expression userInfo.i
in console.log(i + userInfo.i)
will be like this userInfo.name
(as i
will take key name
for the first iteration).
So as we discussed earlier that in the case of dot notation .
we cannot access the value of a variable to access or add a key in an object.
Similarly in the above example, variable i
is holding the keys of the object userInfo
(one key per iteration) and we are using this variable i
to access the key using Dot notation .
. So instead of accessing the value of i
in each iteration, userInfo.i
is accessing i
as the name of the key and as we dont have any key named as i
in object userInfo
thats why we are getting undefined
in each iteration.
If we give a key named i
inside the object userInfo
then the Dot notation .
will access that key named i
instead of printing undefined
.
const userInfo = {
name: "Abhay",
id: 1234,
colors: "blue",
i: "now its a key",
};
for(let i in userInfo){
console.log(i + userInfo.i);
};
//Output:
// name now its a key
// id now its a key
// colors now its a key
// i now its a key
So with the above example, we can say that Dot notation .
in userInfo.i
considers i
as the key name instead of considering the value of i
as the key name for each iteration.
So to overcome this problem we use Bracket notation []
to access the value of the variable i
and access the key from the object userInfo
,
const userInfo = {
name: "Abhay",
id: 1234,
colors: "blue",
};
for(let i in userInfo){
console.log(i + userInfo[i]);
};
//Output:
// name Abhay
// id 1234
// colors blue
Summary:
Object has key-value pairs inside it and each key-value pair is known as a property of that object.
We can access the key of an object using Dot notation
.
or Bracket notation.
.With Dot notation
.
:cannot access the value of a variable while accessing or adding a key to an object.
cannot use multi-word key names with Dot notation
.
In Destructuring, variable name should be same as the name of the key whose value we are trying to access from the object.
for in loop is used to iterate over the keys of an object. To read more about loops in brief.