Introduction
JavaScript has various data types, but primitive data types can hold only a single value at a time. Non-primitive data types, such as Arrays and Objects, tackle this limitation as they can store multiple values within a single variable. Arrays and Objects are among the most useful data types in JavaScript because they allow efficient storage and manipulation of multiple values. We will be diving deep into Objects into this blog.
Objects
An Object in Javascript is a collection key-value pairs .The keys are also called as property in objects amd they are string , values can be of any datatype number,string,boolean. There are three ways to create Objects
1.Object literal{} (most used)
// Basic Syntax for object
let player = {
name: "Msd",
age: 43,
isWicketKeeper: true
};
2.Using new object ()
let car = new Object(); // Empty object is created with name car
car.brand = "Toyota"; // brand property is assigned a value as Toyota
car.model = "Corolla"; // brand model is assigned a value as Corolla
car.year = 2022; // brand year is assigned as 2022
3.Object.create ()
let prototypeObject = {
greet() {
console.log(`Hello ${user.name}`);
}
};
let user = Object.create(prototypeObject);
user.name = "Coders";
user.greet(); // Hello Coders
Accesing Object Properties
In the above code snippet we have created an Object named player having three properties , to access objects properties value we have two ways 1. Dot Notation (.) 2. Bracket Notation ([])
1.Dot Notation (.)
Syntax to access properties value using dot notation is objectname.property . It is best practise for known property name.
let nameofPlayer = player.name;
console.log(nameofPlayer);
// output
// Msd
2.Bracket Notation ([])
The second way to access object properties value is Bracket Notation ([]) ,syntax for this is objectname [property]. It is best practise when key is coming from user input.
let nameofPlayer = player[name];
console.log(nameofPlayer);
// output
// Msd
Modifying Object Properties
Javascript Objects are mutable so this means they can be modified , we can modify property by assigning it to different value . Syntax for this is objectName[property] = newValue.
let programming ={
language: "Python",
use: "AI-ML",
}
console.log(programming.language);// output: Python
programming.language = "Javascipt";
programming["use"] = "Web Development";
console.log(`The ${programming.language} is used for ${programming.use}`);
// output The Javascipt is used for Web Development
Adding New Properties to Object
Javascript Objects are dynamic meaning that they can increase their size based on elements unlike primitive datatypes , we can add new Property to an existing object by writing syntax objectName.newProperty and assigning it value.
let programming ={
language: "Python",
use: "AI-ML",
}
console.log(programming);
// output
// { language: 'Python', use: 'AI-ML' }
programming.instructor = "Hitesh Sir";// this will create new property named instructor in programming object
console.log(programming);
// output
// { language: 'Python', use: 'AI-ML', instructor: 'Hitesh Sir' }
Removing Object Property
Removing Object Property is too simple we just need to use delete keyword and specify property we want to delete from object.
let programming ={ language: 'Python', use: 'AI-ML', instructor: 'Hitesh Sir' }
delete programming.use // This will delete use property from programming object
console.log(programming);
// output
// { language: 'Python', instructor: 'Hitesh Sir' }
Checking if Property Exists in Object
We can check if certain property exists in object by two methods.
1 . Using in
in keyword is used to check if certain value is present in given variable or not , it returns boolean value based on presence of value.
let programming ={ language: 'Python', use: 'AI-ML', instructor: 'Hitesh Sir' }
let present = "use" in programming;
console.log(present);
\\ output will be true as use property is there in programming
2.hasOwnProperty()
This method does same job as in keyword ,it is object specific method . We need to pass property we want to check in argument, it will return boolean value based upon it.
let programming ={ language: 'Python', use: 'AI-ML', instructor: 'Hitesh Sir' }
console.log(programming.hasOwnProperty('teacher'));
// output : false
Key point to remember while checking if property exists in object is we need to pass object property as argument in string form.
Iterating over Objects in Javascript
Objects are not iterable like arrays , it has different ways to iterate over object than arrays .
1.For in loop
For in loop iterates over objects , it allows us to access each key or propertyName of objects and using object.key we can get values of object while iterating over loop.
let sports = {
cricket: "Virat Kohli",
football: "Sunil Chhetri",
chess: "D Gukesh",
athletics: "Neeraj Chopra",
};
for (let key in sports) {
console.log(`The famous player of sport ${key} is ${sports[key]}`);
}
// output
// The famous player of sport cricket is Virat Kohli
//The famous player of sport football is Sunil Chhetri
//The famous player of sport chess is D Gukesh
//The famous player of sport athletics is Neeraj Chopra
2. Object.keys()
Object.keys() method return an array of all keys present in object , we need to pass objectName as an argument to method.
let sports = {
cricket: "Virat Kohli",
football: "Sunil Chhetri",
chess: "D Gukesh",
athletics: "Neeraj Chopra",
};
console.log(Object.keys(sports));
// output : [ 'cricket', 'football', 'chess', 'athletics' ]
3.Object.values()
Object.values(objectname) returns an array of all the values present in object.
let sports = {
cricket: "Virat Kohli",
football: "Sunil Chhetri",
chess: "D Gukesh",
athletics: "Neeraj Chopra",
};
console.log(Object.values(sports));
// Output: [ 'Virat Kohli', 'Sunil Chhetri', 'D Gukesh', 'Neeraj Chopra' ]
4.Object.entries()
This method returns key value pair as an array.
let sports = {
cricket: "Virat Kohli",
football: "Sunil Chhetri",
}
console.log(Object.entries(sports));
// output : [ [ 'cricket', 'Virat Kohli' ], [ 'football', 'Sunil Chhetri' ] ]
Object Methods
Object methods are function inside objects, they can be accesed outside object ny syntax objectName.functionName()
let user = {
name: "Jack",
greet() {
console.log(`Hello, my name is ${this.name}!`); // this refers to an object itself
}
};
user.greet(); // Hello, my name is Jack!
Nested Objects
Nested Objects are an objects containing an another object , we can access inner object’s properties by syntax OuterObject.Innerobject.property.Let’s understand Nested Objects through an example.
let company = {
name: "Learnyst",
location: "Jaipur",
employees: {
manager: "Hitesh Chaudhary",
developers: ["Anirudh", "Akash"]
}
};
console.log(company.employees.manager); // Hitesh Chaudhary
console.log(company.employees.developers[0]); // Anirudh
Copying Object
We can copy one object’s contain into an another one but it is different from how we copy variables . Let’s understand this using memory.
Memory-Types
1.Stack Memory
All primitive data types in JavaScript use stack memory to store variables. Stack memory is static and cannot grow in size, which is why data types with a fixed size are stored directly in it. When variables stored in stack memory are copied, their actual values are duplicated, so any changes made to the copied value do not affect the original variable.
2.Heap Memory
Non-Primitive Datatypes like Objects and Arrays use heap memory to store variables. Heap memory is dynamic and can grow in size ,which is why data types which do not have fixed size are stored in it. When variables stored in heap memory are copied, only their reference (memory address) is duplicated, so any changes made to the copied reference affect the original object.
Now you have the basic overview about memory and how variables are stored in memory , we have two ways to copy objects 1.Shallow copy 2.Deep copy .
1.Shallow Copy
A shallow copy creates a new object but only duplicates the top-level properties. If the object contains nested objects (or arrays), their references are copied instead of their actual values. As a result, modifying a property of the nested object will also affect the original object since both share the same memory address.
Shallow Copy of an object can be created by using spread (….) operator or Object.assign() method.
1.spread (….) operator
let obj1 = { name: "Akash", details: { age: 25 } };
let obj2 = { ...obj1 };
obj2.details.age = 30;
obj1.name = "Mukul";
console.log(obj1.details.age);// 30 (shared reference)
console.log(obj1.name) // Mukul (seperate copy)
console.log(obj2.name) // Akash (seperate copy)
2.Object.assign()
let obj1 = { name: "Akash", details: { age: 25 } };
let obj2 = Object.assign({}, obj1);
obj2.details.age = 30;
console.log(obj1.details.age); // 30 (shared reference)
2.Deep Copy
Deep Copy creates a completely new object without sharing any reference between two , modifying one does not affect other . The process for creating a deep copy using JSON.stringify() involves first converting the object into a JSON string using JSON.stringify(). Then, this string is parsed back into a new object using JSON.parse(), resulting in a completely independent copy of the original object.
let obj1 = { name: "Akash", details: { age: 25 } };
let obj2 = JSON.parse(JSON.stringify(obj1));
obj2.details.age = 28;
console.log(obj1.details.age); // 25 (original remains unchanged)
Thanks for Reading! I hope you enjoyed reading this blog and learnt a lot about Objects ,I’d love to your thoughts in comments and If you found this blog helpful don’t forgot to like it and also check my other Blogs.