Objects in JavaScript

Understand Object in JavaScript Basics

Objects in JavaScript

Object, it's one of the most commonly used data structure in JavaScript. Understanding the object is very important. In this article, I'll share my understanding of what of an object is.

What is an Object ?

An object is a collection of properties having name-value pairs, or we can also say that An object is a collection of data – or key value pairs.

Object Creation

An object can be created with curly brackets {....} with an optional list of properties. A property is a "key:value" pair, where the key is a string (also called a "property name"), and the value can be anything like string, integer, boolean, or cloud be another object or even a function.

const person = {        //an  person object
 name : "ajay",              //by key "name"  store value "ajay"   type of string
 state : "gujarat",         
 id : 1,                          // by key "id" store value "1" type of number
isHosteler: true,             //   key "isHosteler"  value "true"  type  boolean
Courses: ['javascript', 'ReactJS' ],      //array
}
  1. In this object, first property has name and the value is ajay
  2. the second one has property state and the value is gujarat
  3. the third one has property id and value is 1

Create Object Using a new Keyword

We can also use this method for creating an object. Using this method, you can first create an object using the new keyword and then add properties to it later.

let user  = new Object();
user.name : "ajay"
user.state : "gujarat"
user.id = 1

Using Constructor

The regular {...} syntax allows creating one object. But often we need to create many similar objects, like multiple users or so on. A constructor is a special method that is automatically called when an object is created. Constructors are code snippets that run while creating an object. We can optionally pass parameters while the creation of an object using a new keyword.

const User = function(name , state , id){
  this.name = name;
  this.state = state;
  this.id = id   
}
const user1 =  new User("ajay" , "gujarat" ,1)

Accessing the Properties of an Object

1. Dot Notation

Dot notation is where we can call that key value pair (which is known as a property) and pulls that information.

const person = { 
 name : "ajay",                           
 state : "gujarat", 
 id : 1,                                         
isHosteler: true,                                 
Courses: ['javascript', 'ReactJS' ],       
}

console.log(person.name);          // output :  ajay
console.log(person.state);           // gujarat
console.log(person.Courses);     //  ['javascript', 'ReactJS' ]

2.Using the square brackets []

We can also access the object by using the square brackets []. Square brackets notation obj["property"]. Square brackets allow to take the key from a variable, like obj[varWithKey].

const person = { 
 name : "ajay",                           
 state : "gujarat", 
 id : 1,                                         
isHosteler: true,                                 
Courses: ['javascript', 'ReactJS' ],       
}
console.log(person['name']);        //output :   ajay
console.log(person['isHosteler']);  //  true
console.log(person['id']);   // 1

Object Iteration

An object has a key and value. In array, we simply iterate the array, but in object we can't do that. For iterating an object it has own some method, lets see.

Object.keys()

This method returns the keys of an object in an array

const user = {
  name: 'ajay',
  id: 20,

}
console.log(Object.keys(user)); //   ["name", "id"]

Object.values()

This method is like object.keys but it returns the value of the properties in an array.

const user = {
  name: 'ajay',
  id: 20,

}
console.log(Object.values(user)); //   ["ajay", 20]

Object.entries()

Object.entries() method returns a multi-dimensional array which contains an array of key-value pair of the object's properties.

const user = {
  name: 'ajay',
  id: 1,

}
const kp = Object.entries(user)

console.log(kp); 
// output
(2) [Array(2), Array(2)]
0: Array(2)
0: "name"
1: "ajay"
1: Array(2)
0: "id"
1: 1

This is same as the as iterating with a for...in loop.

const user = {
  name: 'ajay',
  id: 1,

}
const kp = Object.entries(user)


for(let [key ,value]  of kp){
  console.log(`${key} : ${value}`);  
}
//output 
name : ajay 
id : 1

The "for..in loop" in Object

To walk over all keys of an object, there exists a special form of the loop: for..in. let's see by example, how it's work

const person = { 
 name : "ajay",                           
 state : "gujarat", 
 id : 1,                                         
isHosteler: true,                                 
Courses: ['javascript', 'ReactJS' ],       
}

for(let key in person){
   console.log(key);   //       name ,  state ,  id ,  isHosteler , Courses
   console.log(person[key]);    //  ajay , gujarat , 1 , true ,   ['javascript', 'ReactJS' ],  
 }

Object references and copying

One of the fundamental differences of objects versus primitives is that objects are stored and copied “by reference”, whereas primitive values: strings, numbers, boolean, etc – are always copied “as a whole value”. Let's see primitive, if we create a variable, then copy this variable in another variable, so both are independent variables.

let msg = "hey"
 let newMsg = msg 
console.log(msg==newMsg);    // true

newMsg = "hello"
console.log(msg==newMsg);   // false

But object are not like that. A variable assigned to an object stores not the object itself, but its “address in memory” – in other words, “a reference” to it. The object is stored somewhere in memory, while the user variable has a “reference” to it. When an object variable is copied, the reference is copied, but the object itself is not duplicated. let's see by an example

const person = { 
  id : 1,                                         
  name : "ajay",                           
 } 
 const person2 = person  //copy  the reference

Now we have two variables, each storing a reference to the same object. If now I will change in person2 name and ID, and print both, let's see what happen

const person = { 
  id : 1,                                         
  name : "ajay",                           
 } 
 const person2 = person

 person2.id = 2;
 person2.name = "virat"

 console.log(person);     //   {id :2 , name : "virat"}
 console.log(person2);  // {id :2 , name : "virat"}

It's amazing right, even I make a new person2 and assign person into this, and change the person2 values, but it also changes the person value even I don't change person value. It happens because when person2 variable assign to person, then it also receives a reference of the same address location of the object person {id: 1, name : "ajay"} and hence the console.log(person2===person) will output the value of 'true'.

Comparison

It is very simple to compare the primitive values in JavaScript. But comparing the objects is not so easy because objects are structured data. When we use == or === operator, they only compare the references of the objects. Two objects are equal only if they are the same object.

const person = { 
  id : 1,                                         
  name : "ajay",                           
 } 
 const person2 = person
console.log(person===person2);  // true  both variables reference the same object

And here two independent objects are not equal, even though they look same

const person = { 
  id : 1,                                         
  name : "ajay",                           
 } 
 const person2 = { 
  id : 1,                                         
  name : "ajay",                           
 }
 console.log(person===person2); //false  two independent objects

So, copying an object variable creates one more reference to the same object. But what if we need to duplicate an object? Create an independent copy, a clone? It's difficult because here’s no built-in method for that in JavaScript. But there is rarely a need But if we want to do that, let's see how we can do that.

Cloning

const person = { 
  id : 1,                                         
  name : "ajay",                           
 } 
const newPerson = {} 

for(let key in person){
  newPerson[key] = person[key]
}
newPerson.num = 23

console.log(person); //  {id : 1 , name : "ajay"}

console.log(newPerson);  // { id :1 ,  name : 'ajay' , num :23}

console.log(newPerson === person); // false

So that's it for now.

If you want to read more on this, refer Object MDN Object Basics

Thanks for reading till now 🙏

You can connect 👋 with me on LinkedIn, Twitter GitHub