DEV Community

Hemendra Khatik
Hemendra Khatik

Posted on • Updated on • Originally published at blog.aamchora.space

JavaScript objects in depth.

Being a JavaScript developer, you might be aware of the fact that we can't build any large-scale app without dealing with Objects.

In JavaScript, Almost everything is an Object.

Lets, Deep dive into JavaScript Objects.

Object: Objects in JavaScript are nothing but a non-primitive type data structure. We can define an object using curly brackets and put key-value pairs separated by a comma in it.

EG:

const user = {
   name:"Hemendra",
   nickname:"Hemu",
   email:"hi@aamchora.space",
   city:"bhilwara"
}
Enter fullscreen mode Exit fullscreen mode

CRUD operations on an object

Create

let student = {}; // an empty array

student.name = "Hemendra Khatik"; 
//important -> student["name"]="Hemendra Khatik" is also valid

student.branch = "CSE";
student.age = 25;

console.log(student); // will print the below structure
/*
{
   name:"Hemendra Khatik",
   branch:"CSE",
   age:25
}
*/
Enter fullscreen mode Exit fullscreen mode

or all key values at once

let user = {
   name:"Hemendra",
   nickname:"Hemu",
   email:"hi@aamchora.space",
   city:"bhilwara"
}
Enter fullscreen mode Exit fullscreen mode

Read

We use . operator to access the values of an object.

user.name; // to access the "Hemendra".
user.city; // to access the "bhilwara".
user.username; // will be undefined because it is not present in the user object.
Enter fullscreen mode Exit fullscreen mode

We can also access properties of an object using square brackets.

user["name"];    // to access the "Hemendra".
user["city"];    // to access the "bhilwara".
Enter fullscreen mode Exit fullscreen mode

Update

Update an object .

student.age = 21; // now age is changed from 25 to 21
Enter fullscreen mode Exit fullscreen mode

Delete

Delete key from an object.

delete student.name; // to delete the name key from student object
Enter fullscreen mode Exit fullscreen mode

Other Helpful methods

print the keys only from an object.

const user = {
   username:"aamchora",
   email:"hi@aamchora.space",
};

Object.keys(user);
/* 
Above expression returns an array containing 
keys only from an object ["username", "email"]
*/
Enter fullscreen mode Exit fullscreen mode

print the values only from an object.

const user = {
   username:"aamchora",
   email:"hi@aamchora.space",
};

Object.values(user);
/* 
Above expression returns an array containing 
values only from an object ["aamchora", "hi@aamchora.space"]
*/
Enter fullscreen mode Exit fullscreen mode

Freeze the JavaScript Object

const user = {
   username:"aamchora",
   email:"hi@aamchora.space",
};

Object.freeze(user);
/* 
Above expression freezes the object. 
It means we cannot add, remove or update its properties.
It will not throw any error unless you are in strict mode but
there will be no effect of value change on your object.
*/

user.username = "NewUserName"; // --> will not work
user.newKey = "xyz"; // --> will not work
delete user.email; // --> will not work

console.log(user);
/*
{
  username:"aamchora",
  email:"hi@aamchora.space",
}
*/
Enter fullscreen mode Exit fullscreen mode

Cloning an object

You can not copy non-primitive type data structure as you copy primitive type data structure.

EG: Non-primitive type data structure.

let a = 10;
let b = a;
b= b + 1;
console.log(a) // 10
console.log(b) // 11
Enter fullscreen mode Exit fullscreen mode

EG: Primitive type data structure.

let obj = {
 a:10;
};
let obj2 = obj;
obj2.a = 12;

if(obj === obj2){
   console.log("obj and obj2 are same");
};
// above condition will be true 

console.log(obj) // {a:12}
console.log(obj2) // {a:12}

Enter fullscreen mode Exit fullscreen mode

To understand this weird behavior of JavaScript, you can read below blog.

Click here to read

We can use Object.assign(targetObject, sourceObject) to clone an object.

const obj = { a: 1 };
const obj2 = Object.assign({}, obj);
obj2.a = 2;

if(obj === obj2){
   console.log("obj and obj2 are same");
}else{
 console.log("obj and obj2 are different");
};

// above condition will be false here 

console.log(obj); // { a: 1 }
console.log(obj2); // { a: 2 }
Enter fullscreen mode Exit fullscreen mode

Shallow copy
A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made.

Note: For Shallow copy we use Object.assign(targetObject, sourceObject).

Look at below example to understand Shallow copy.

const obj = {
 a:1
}

const obj2 = {
 b:2,
 c:obj // here c's value is a reference to the other object called obj
}

const copy = Object.assign({},obj2); // here obj2 is a source object 

// changing the copied object's value 
copy.c.a = 1111;


if(copy.c.a === obj.a){
   console.log("obj and obj2 are same");
}
// above condition will be true 

Enter fullscreen mode Exit fullscreen mode

Deep copy

A deep copy of an object is a copy whose properties do not share the same references(point to the same underlying values) as those of the source object from which the copy was made.

Note: For Deep copy we use JSON.parse(JSON.stringify(sourceObject)).

Look at below example to understand Deep copy.

const obj = {
 a:1
}

const obj2 = {
 b:2,
 c:obj // here c's value is a reference to the other object called obj
}

const copy = JSON.parse(JSON.stringify(obj2)) // here obj2 is a source object 

// changing the copied object's value 
copy.c.a = 1111;


if(copy.c.a === obj.a){
   console.log("obj and obj2 are same");
}else{
  console.log("obj and obj2 are not same");
}
// above condition will be false 

Enter fullscreen mode Exit fullscreen mode

follow me for more such blog posts.
Let me know if this blog was helpful.

Discussion (4)

Collapse
link2twenty profile image
Andrew Bone

Hello!

If you'd like, you can add syntax highlighting (colours that make code easier to read) to your code block like the following example.

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

This should make it a bit easier to understand your code. 😎

In order to use this in your code blocks, you must designate the coding language you are using directly after the first three back-ticks. So in the example above, you'd write three back-ticks js (no space between the two), put the code beneath (e.g. console.log('Hello world!');), then three back-ticks beneath that to close the code.

Here's an image that shows how it's written!

Example of how to add syntax highlighting in code blocks

Collapse
aamchora profile image
Hemendra Khatik Author

Woww it's really cool thanks a lot.

Collapse
oz profile image
Evgenii OZ

There is one more way to clone an object: developer.mozilla.org/en-US/docs/W...

Collapse
aamchora profile image
Hemendra Khatik Author

Thanks for sharing :)