👉Objects in JavaScript 👈

Rahul Kumar
6 min readJul 20, 2023

--

What are Objects?

  • An object consists of state and behavior.
  • State: The State of an entity represents properties that can be modeled as key-value pairs.
  • Behavior: The Behavior of an entity represents the observable effect of an operation performed on it and is modeled using functions.

Example:

A Car is an object in the real world.

State of Car object:

  • Color=red
  • Model = VXI
  • Current gear = 3
  • Current speed = 45 km / hr
  • Number of doors = 4
  • Seating Capacity = 5

The behavior of Car object:

  • Accelerate
  • Change gear
  • Brake

Types Of Objects:

Ways Of Creating Object:

Creating Objects by Objects Literals:

  • Objects can be created using object literal notation.
  • Object literal notation is a comma-separated list of name-value pairs wrapped inside curly braces. This promotes the encapsulation of data in a tidy package. This is how the objects in JavaScript are created using the literal notation:

Syntax:

objectName = {
//-------------states of the object-----------
key_1: value_1,
key_2: value_2,
...
key_n: value_n,
//-------------behaviour of the object---------
key_function_name_1: function (parameter) {
//we can modify any of the property declared above
},
...
key_function_name_n: function(parameter) {
//we can modify any of the property declared above
}
}

example:

//-------------states of the object--------- 
let myCar = {
name: "Fiat",
model: "VXI",
color: "red",
numberOfGears: 5,
currentGear: 3,
currentSpeed: 45,

//-------------Behaviour of the object---------
accelerate: function (speedCounter) {
this.currentSpeed = this.currentSpeed + speedCounter;
return this.currentSpeed;
},

brake: function (speedCounter) {
this.currentSpeed = this.currentSpeed - speedCounter;
return this.currentSpeed;
}
}

Creating Object using Enhanced Object Literals →Property Shorthand:

//Literal property without shorthand 
function createCourse(name, status) {
return {type: "JavaScript", name: name, status: status};
}
function reviewCourse(name) {
return {type: "JavaScript", name: name};
}
/*Literal property with shorthand
when the property and the value identifiers have the same name,
the identifier can be omitted to make it implicit*/
function createCourse(name, status) {
return {type: "JavaScript", name, status};
}
function reviewCourse(name) {
return {type: "JavaScript", name};
}

Creating Object using Function Constructor:

function Car(name, model, color, numberOfGears, currentSpeed, currentGear) { 
//-------------States of the object---------
this.name = name;
this.model = model;
this.color = color;
this.numberOfGears = numberOfGears;
this.currentSpeed = currentSpeed;
this.currentGear = currentGear;
//-------------Behaviour of the object---------
this.accelerate = function (speedCounter) {
this.currentSpeed = this.currentSpeed + speedCounter;
return this.currentSpeed;
}
this.brake = function (speedCounter) {
this.currentSpeed = this.currentSpeed - speedCounter;
return this.currentSpeed;
}
}

myCar = new Car('Tesla','XL','black',5,200,5);
console.log(myCar.name);
console.log(myCar.currentSpeed);
console.log(myCar.accelerate(50));//invokes accelerate() with argument = 50
console.log(myCar["name"],myCar["currentSpeed"],)

Combining and cloning Objects using Spread operator:

  • The spread operator is used to combine two or more objects. The newly created object will hold all the properties of the merged objects.

syntax:

let object1Name = { 
//properties
};
let object2Name = {
//properties
};
let combinedObjectName = {
...object1Name,
...object2Name
};
//the combined object will have all the properties of object1 and object2

Example:

let candidateSelected={
Name:'Rexha Bebe',
Qualification:'Graduation',
};
let SelectedAs={
jobTitle:'System Engineer',
location:'Bangalore'
};
let employeeInfo={
...candidateSelected,
...SelectedAs
};
console.log(employeeInfo);
/*
{
Name: 'Rexha Bebe',
Qualification: 'Graduation',
jobTitle: 'System Engineer',
location: 'Bangalore'
}
*/

Combining and cloning Objects using Spread operator:

It is possible to get a copy of an existing object with the help of the spread operator.

Syntax:

let copyToBeMade = { ...originalObject };

Example:

let originalObj = { one: 1, two: 2, three: 3 };
let clonedObj = { ...originalObj };
/*
Here spreading the object into a list of parameters happens
which return the result as a new object
checking whether the objects hold the same contents or not
*/
console.log(originalObj);
clonedObj.four = 4;
console.log(clonedObj);

/* Output:
{ one: 1, two: 2, three: 3 }
{ one: 1, two: 2, three: 3, four: 4 }
*/

De-structuring Objects:

  • De-structuring gives a syntax that makes it easy to create objects based on variables.
  • It also helps to extract data from an object. De-structuring works even with the rest and spread operators.

In the below example an object is de-structured into individual variables:

let myObject = { name: 'Arnold', age: 65, country: 'USA' };
let { name, age:currentAge } = myObject; //alias can be used with :
console.log(name);
console.log(currentAge);
//OUTPUT: Arnold 65

An alias currentAge is used for age.

Object de-structuring in functions:

let myObject = { name: 'Marty', age: 65, country: 'California' }; 
function showDetails({ country }) {
console.log(country);
}
showDetails(myObject); //invoke the function using the object
//OUTPUT: California

Accessing Object Properties:

Syntax:

  • For retrieving state/behavior value:
objectName.key;
//OR
objectName[key];
  • For setting state/behavior value:
objectName.key = value;
//OR
objectName[key] = value;

Example:

//-------------states of the object--------- 
let myCar = {
name: "Fiat",
model: "VXI",
color: "red",
numberOfGears: 5,
currentGear: 3,
currentSpeed: 45,

//-------------Behaviour of the object---------
accelerate: function (speedCounter) {
this.currentSpeed = this.currentSpeed + speedCounter;
return this.currentSpeed;
},

brake: function (speedCounter) {
this.currentSpeed = this.currentSpeed - speedCounter;
return this.currentSpeed;
}
}

// Accessing object properties
console.log(myCar.name);
console.log(myCar.color);

// Setting object properties
myCar.color = 'Black';
console.log(myCar.color);


/*
Output:
Fiat
red
Black
*/

Accessing object properties using for…in loop:

  • To work with all the keys of an object, there is a particular form of the loop: for…in. This is a different way from the for() construct.

Syntax:

for (key in object) { 
// executes the body for each key among object properties
}

Example:

let user = {
name: "Rexha",
age: 24,
isConfirmed: true
};
for (let key in user) {
console.log(`${key} : ${user[key]}`); // values for the keys
}

/*
Output:
name : Rexha
age : 24
isConfirmed : true
*/

Built-In Global Objects:

  • The Global object allows to declare variables and functions that can be accessed anywhere.
  • By default, these are built into the language or the environment.

They are different built-in objects in JavaScrip:

  • Date
  • Array
  • String
  • Math
  • RegEx
  • JSON

Date:

  • The built-in JavaScript object ‘Date’ allows us to work with dates and times displayed as part of the web page. It can be instantiated wherever required using one of the many constructors available.

Example:

let dateObject1 = new Date(); 
console.log("Date is: " + dateObject1); // print date of today

Example2:

let  dataObject2 = new Date(2020, 5, 18, 22, 20, 23, 0000); 
console.log("Date is: "+dataObject2);
//OUTPUT: Date is: Thu Jun 18, 2020, 22:20:23 GMT+0530 (India Standard Time)
// Getter methods of Date:
let dateObject3 = new Date();
console.log("Date is: " + dateObject3.getDate());
console.log("Day is: " + dateObject3.getDay());
console.log("Year is: " + dateObject3.getYear());
console.log("Horrs: " + dateObject3.getHours());
console.log("Month is: " + dateObject3.getMonth());
console.log("Time is: " + dateObject3.getTime());
console.log("Millisecond: " + dateObject3.getMilliseconds());
/*
OUTPUT:
Date is: 23
Day is: 2
Year is: 123
Horrs: 16
Month is: 4
Time is: 1684840771892
Millisecond: 892
*/

Example:

let dateObject1 = new Date(); 
dateObject1.setDate(3);
dateObject1.setYear(1996);
dateObject1.setHours(8);
dateObject1.setMonth(7);
dateObject1.setMilliseconds(2000);

console.log("Date is: " + dateObject1.getDate());
console.log("Year is: " + dateObject1.getYear());
console.log("Hours: " + dateObject1.getHours());
console.log("Month is: " + dateObject1.getMonth());
console.log("Millisecond: " + dateObject1.getMilliseconds());
/*
OUTPUT:
Date is: 3
Year is: 96
Hours: 8
Month is: 7
Millisecond: 0
*/

--

--