Winning the Race in Formula 1 - Using Objects in JavaScript


Introduction
In JavaScript, an object is a collection of key-value pairs where the keys (also called properties) are strings or symbols, and the values can be any data type, including other objects and functions.
Objects are basically real-world entity . let's take an example of a car , lets say you want to know all the details of car, we can define it with different data types but with object we can define everything to a car object . You are in an f1 race and you want to know everything about the car ,lets take object and see how we can win the race .
Checking out the car model - initializing a car object
const f1Car = {
brand : 'Toyota',
model : "supra",
color : "Black",
}
we can also initialize the car with few different methods
using new Object()
const car = new Object();
car.brand = "Toyota";
car.model = "supra";
car.color = "Black"
console.log(car.brand); // Toyota
Using a Constructor Function
function Car(brand,model,color){
this.brand = brand;
this.model = model;
this.color = color
}
const f1Car = new Car("toyota","supra","Black")
Let's See How we can Start the car
const f1Car = {
brand : 'Toyota',
model : "supra",
color : "Black",
//initial speed of the car
speed : 0,
//method to start the car
start: function(){
console.log(`starting the car ${this.brand} ${this.model}`)
console.log(`Bhrrum Bhruum ....`)
}
//Since its supra we need to accelarate
accelerate:function(amount){
this.speed += amount;
console.log(`The car is flying at the speed of ${this.speed}`)
}
//stop the car
stop:function(){
this.speed = 0;
console.log("The Beast has stopped")
}
}
Driving the car : Accessing object properties
// Want to know the brand of the car
// Also known as the Dot Notation
car.brand //toytota will be printed
//we can also access the brand as
// Also known as bracket Notaion
car['brand']
// the model of the car
car.model // supra will be printed
//we can also access the model as
car['model']
//color of the car
car.color // black will be printed
//we can also access the color as
car['color']
car.start() //we wil start the car
car.accelerate(30) // we will accelerate the car with 30km/ph
//but since its supra we can't go so slow
car.accelerate(120) // now the car will go at the speed of 150
car.stop() // to stop the car
Now let's understand what properties, methods and this keyword
Properties:
brand
,model
,color
, andspeed
store details about the car.
Methods (Functions inside objects):
start()
: Prints a message when the car starts.accelerate(amount)
: Increases the car’s speed.stop()
: Resets speed to 0.
this
Keyword:Refers to the current object (
car
) inside methods.Example:
this.speed += amount;
modifies the car's speed.
Suppose we want to change the color of the car - Modifying Objects
car.color = "Red"
console.log(car.color); // Red
we changed the color of the car to Red
The Organizers and announced the list of Car's that can Participate - we want to make a copy of the List
Shallow copy
A shallow copy means only the first-level properties are copied , while nested objects still reference the original object.
Shallow copy means we can just copy the name and won't be able to copy the properties of objects in car objects , it will just take a reference if we do any changes in our copy then it will change in the main list.
const carList = {
engine : "V4",
carOne : {
brand: "toyota",
model : "supra",
color : "black"
},
carTwo : {
brand: "Ford",
model : "Mustang"
color : "Black"
},
}
const myCarlist = {...carList};
// Now if i want to change the engine it won't effect the main carList, only my copied lists engine will change
myCarList.engine = "V3";
// Now if i try to see the list
myCarList.engine // it will print V3
CarList.engine // it will print V4
//Now if i want to change the color of the carOne in my list it will also effect the main List (carList)
myCarList.carOne.color = "red"
//Now if i try to see both the list
myCarList.carOne.color // it will print red
carList.carOne.color // it will change from black to red - my main list also go chager because it is a shallow copy
We can Make shallow copy in two ways
// Using the Spread(...) operator
const myCarList = {...carList}
// Using the Object.assign()
const myCarList = Object.assign({},carList)
Some issues that may arise while using shallow copy -
The Nested Object address is shared between carList and MyCarList
changing carList.carOne.color also effects carList.carOne.color
Deep Copy ( Full Copy)
A deep copy creates a completely independent clone of an object, including all nested objects.
A deep copy will create a new list which won't effect the list given by the Organizers, we will have a totally independent copy to ourself.
const carList = {
engine : "V4",
carOne : {
brand: "toyota",
model : "supra",
color : "black"
},
carTwo : {
brand: "Ford",
model : "Mustang"
color : "Black"
},
}
const myCarlist = JSON.parse(JSON.stringfy(carList))
// Now if i want to change the engine it won't effect the main carList, only my copied lists engine will change
myCarList.engine = "V3";
// Now if i try to see the list
myCarList.engine // it will print V3
CarList.engine // it will print V4
//Now if i want to change the color of the carOne in my list it will not effect the main list since we have a deep copy
myCarList.carOne.color = "red"
//Now if i try to see both the list
myCarList.carOne.color // it will print red
carList.carOne.color // it will print black , since we have a deep copy
Different ways to make Deep Copy
// Using JSON.parse(JSON.stringify(carList))
const myCarList = JSON.parse(JSON.stringify(carList));
//Using Lodash's -.cloneDeep() method
const myCarList = _.cloneDeep(carList)
// Using a Recursive Function
function deepCopy(carList){
if(carList == null || typeof carList !== "object") return obj
let copy = {}
for( let key in carList){
copy[key] = deepCopy(carList[key])
}
retun copy;
}
Now we want to see all the car's that's Participating - Looping through an Object
for...in
loop
- to see all the cars in the list
for (let key in carList)
{ console.log(`${car}: ${carList[key]}`);
}
- Now we want to check if a Property of a car exists or nor
carList.hasOwnProperty("engine") // retuens true since engine exists in our property
- Object Destructuring
const {engine,carOne,cartwo} = carList;
- Object Freezing & Sealing
Object.freeze(carList); // Prevents adding, removing, or modifying properties
carList.color = "blue"; // Won't change the color
Object.seal(carList); // Allows modifying but prevents adding/removing properties
Conclusion
Objects in JavaScript are one of the most fundamental data structures, allowing us to store and manage data efficiently. They act as collections of key-value pairs, making it easy to group related information and behaviors together. We explored how to create objects using literals, constructors, and Object.create()
, as well as different ways to access, modify, and loop through object properties.
Understanding shallow and deep copies is crucial when working with objects, as JavaScript assigns object references rather than copying them by default. Techniques like the spread (...
) operator, Object.assign()
, and deep cloning methods such as JSON.parse(JSON.stringify(obj))
and _.cloneDeep()
ensure that objects are copied appropriately based on the use case.
Mastering objects is essential for writing clean, efficient, and scalable JavaScript code. Whether you're dealing with simple key-value storage, managing state in an application, or working with APIs, objects play a vital role in modern JavaScript development. By applying best practices, you can make your code more organized, maintainable, and powerful. 🚀
If you have found this article useful , or want to improve then send a remark ,appreciate your feedback and time for reading the article
Subscribe to my newsletter
Read articles from Muksiduz Zaman directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
