Thursday, 16 January 2025

JavaScript Objects: A Comprehensive Guide for Beginners

Objects are a fundamental part of JavaScript, allowing you to store collections of data and more complex entities. Unlike primitive data types (like numbers, strings, and booleans), objects can hold multiple values as properties and methods.

 

1. What is an Object?

In JavaScript, an object is a collection of key-value pairs where each key is a string (also called a property name) and the value can be any data type, including another object, a function (in which case it is called a method), or a primitive value.

 

2. Creating Objects

There are several ways to create objects in JavaScript

 

2.a Object Literal

The most common way to create an object is by using object literals. An object literal is a comma-separated list of key-value pairs inside curly braces {}.

        

literalNotattion.js

const person = {
  name: "Alice",
  age: 25,
  isStudent: false,
  greet: function() {
    console.log("Hello, my name is " + this.name);
  }
};

console.log(`name: ${person.name}`);
console.log(`age: ${person.age}`);
console.log(`isStudent: ${person.isStudent}`);
person.greet();

Output

name: Alice
age: 25
isStudent: false
Hello, my name is Alice

b. Using new Object()

You can also create an object using the Object constructor.

 

createObjectUsingObjectConstructor.js

const person = new Object();

// Attach properties to the person object
person.name = "Alice";
person.age = 25;
person.isStudent = false;

// Attach functon to the person object
person.greet = function() {
  console.log("Hello, my name is " + this.name);
};

console.log(`name: ${person.name}`);
console.log(`age: ${person.age}`);
console.log(`isStudent: ${person.isStudent}`);
person.greet();

Output

name: Alice
age: 25
isStudent: false
Hello, my name is Alice

c. Using a Constructor Function

For creating multiple similar objects, you can use a constructor function.

 

objectCreationUsingConstructorFunction.js

function Person(name, age, isStudent) {
  this.name = name;
  this.age = age;
  this.isStudent = isStudent;
  this.greet = function() {
    console.log("Hello, my name is " + this.name + "\n");
  };
}

function aboutPerson(person){
  console.log(`name: ${person.name}`);
  console.log(`age: ${person.age}`);
  console.log(`isStudent: ${person.isStudent}`);
  person.greet();
}

const person1 = new Person("Alice", 25, false);
const person2 = new Person("Bob", 30, true);

aboutPerson(person1)
aboutPerson(person2)

Output

name: Alice
age: 25
isStudent: false
Hello, my name is Alice

name: Bob
age: 30
isStudent: true
Hello, my name is Bob

d. Using classes

 

objectCreationUsingClasses.js

class Person {
  constructor(name, age, isStudent) {
    this.name = name;
    this.age = age;
    this.isStudent = isStudent;
  }

  greet() {
    console.log("Hello, my name is " + this.name + "\n");
  }
}

function aboutPerson(person){
  console.log(`name: ${person.name}`);
  console.log(`age: ${person.age}`);
  console.log(`isStudent: ${person.isStudent}`);
  person.greet();
}

const person1 = new Person("Alice", 25, false);
const person2 = new Person("Bob", 30, true);

aboutPerson(person1)
aboutPerson(person2)

Output

name: Alice
age: 25
isStudent: false
Hello, my name is Alice

name: Bob
age: 30
isStudent: true
Hello, my name is Bob

How to access object properties?

You can access the properties of an object using either dot notation or bracket notation.

 

a. Dot Notation

console.log(person.name);

b. Bracket Notation

Bracket notation is useful when the property name is dynamic or not a valid identifier (like property name as spaces etc.,).

console.log(person["age"]);

const prop = "isStudent";
console.log(person[prop]);

accessObjectProperties.js

person1 = {
	id : 1,
	name : "Krishna",
	"place of birth" : "India" 
}

let personId = person1.id;
let name = person1['name'];
let placeOfBirth = person1['place of birth'];

console.log(`personId : ${personId}`)
console.log(`name : ${name}`)
console.log(`placeOfBirth : ${placeOfBirth}`)

Output

personId : 1
name : Krishna
placeOfBirth : India

4. Adding and Modifying Properties

You can add or modify properties of an object after it has been created using either . notation of [] notation.

person.job = "Engineer";
person.age = 26;

modifyObjectProperties.js

person1 = {
	id : 1,
	name : "Krishna",
	"place of birth" : "India" 
}

function aboutPerson(person){
	let personId = person.id;
	let name = person['name'];
	let placeOfBirth = person['place of birth'];

	console.log(`id : ${personId}`);
	console.log(`name : ${name}`);
	console.log(`placeOfBirth : ${placeOfBirth}\n`);
}

aboutPerson(person1);

// Add new property age
console.log('Add new property age');
person1.age = 35;

// Update person name
console.log('Update name to the value "Ram"\n');
person1.name = "Ram";

aboutPerson(person1);
console.log(`age: ${person1.age}`)

Output

id : 1
name : Krishna
placeOfBirth : India

Add new property age
Update name to the value "Ram"

id : 1
name : Ram
placeOfBirth : India

age: 35

5. Iterate over all the properties of an object

You can iterate over an object's properties using a for...in loop.

for (let key in person) {
  console.log(key + ": " + person[key]);
}

iterateOverObjProps.js

person1 = {
	id : 1,
	name : "Krishna",
	"place of birth" : "India" 
}

function printObj(obj){
	for(let property in obj){
		console.log(`${property} : ${obj[property]}`);
	}
}

printObj(person1);

Output

id : 1
name : Krishna
place of birth : India

6. Delete object properties

You can remove properties from an object using the delete operator.

delete person.id;

deleteObjectProperties.js

person1 = {
	id : 1,
	name : "Krishna",
	"place of birth" : "India" 
}

function printObj(obj){
	for(let property in obj){
		console.log(`${property} : ${obj[property]}`);
	}
}

printObj(person1);

console.log('\nDeleting the object property id\n');
delete person1.id;

printObj(person1);


Output

id : 1
name : Krishna
place of birth : India

Deleting the object property id

name : Krishna
place of birth : India

7. Checking for property existence

To check if an object has a specific property, you can use the in operator or hasOwnProperty() method.

 

checkForPropertyExistence.js

person1 = {
	id : 1,
	name : "Krishna",
	"place of birth" : "India" 
}

console.log(`is id exists in person1 : ${"id" in person1}`);
console.log(`is "place of birth" exists in person1 : ${person1.hasOwnProperty("place of birth")}`);
console.log(`is age exists in person1 : ${"age" in person1}`)

Output

is id exists in person1 : true
is "place of birth" exists in person1 : true
is age exists in person1 : false


8. Nested Objects

Objects can contain other objects as properties, allowing for complex data structures.

 

nestedObjects.js

let person1 = {
	id : 1,
	name : "Krishna",
	age : 35,
	address : {
		city : "Bangalore",
		country : "India"
	}
};

console.log(`id : ${person1.id}`)
console.log(`name : ${person1.name}`)
console.log(`age : ${person1.age}`)
console.log(`city : ${person1.address.city}`)
console.log(`country : ${person1.address.country}`)

Output

id : 1
name : Krishna
age : 35
city : Bangalore
country : India

9. Object Destructuring

Destructuring allows you to extract properties from an object and assign them to variables.

 

objectDestructuring.js

let person1 = {
	id : 1,
	name : "Krishna",
	age : 35,
	address : {
		city : "Bangalore",
		country : "India"
	}
};

let {id, name, age, address} = person1;

console.log(`id : ${id}`);
console.log(`name : ${name}`);
console.log(`age : ${age}`);
console.log(`city : ${address.city}`);
console.log(`country : ${address.country}`);

Output

id : 1
name : Krishna
age : 35
city : Bangalore
country : India

10. Object Methods

Objects can have methods, which are functions associated with the object. The this keyword inside a method refers to the object itself.

 

objectMethods.js

let person1 = {
	id : 1,
	name : "Krishna",
	age : 35,
	aboutMe: function(){
		console.log(`id : ${this.id}`);
		console.log(`name : ${this.name}`);
		console.log(`age : ${this.age}`);
	}
};

person1.aboutMe();

Output

id : 1
name : Krishna
age : 35


Objects in the JavaScript form the backbone of how data and functionality are structured. They can store various types of data, including other objects, and can be manipulated in numerous ways.



Previous                                                    Next                                                    Home

No comments:

Post a Comment