An object is a data type that allows you to store key-value pairs.
Object:
- String / number / boolen / null / undefined
- Array
- Function
- Object
//Object Example
let person = {
name: "Happy",
hobbies: ["Teaching", "Football", "Coding"],
greet: function() {
console.log("Name: " + this.name);
}
};
console.log(person.name); // Output: "Happy"
console.log(person.hobbies[1]); // Output: "Football"
person.greet(); // Output: "Name: Happy"
Method | Syntax | Example |
---|---|---|
Object Literal | var objectName = { property1: value1, property2: value2, ... }; |
var person = { name: "Happy", age: 38, role: "Trainer" }; |
Object Constructor | var objectName = new Object(); |
var person = new Object();<br>person.name = "Happy";<br>person.age = 38; |
Object.create() Method | var objectName = Object.create(prototypeObject); |
var person = { name: "Happy", age: 38 };<br>var men = Object.create(person);<br>men.role = "Trainer"; |
Feature | Arrays | Objects |
---|---|---|
Definition | Collections of values. | Collections of key-value pairs. |
Notation | Square brackets [] . |
Curly braces {} . |
Element/Property Order | Ordered. | Unordered. |
//Array
var fruits = ["apples", "banana", "orange"]
var person = {
name: "Adarsh",
age: 25,
city: "Delhi"
}
// Blank object
var person = {};
// Adding Properties
person.name = "Happy";
person.age = 35;
person.country = "India";
// Modifying Properties
person.age = 30;
// Deleting Properties
delete person.age;
Dot Notation vs. Bracket Notation
-
Both dot notation and bracket notation are used to access properties or methods of an object.
-
Dot notation is more popular and used due to its simplicity.
Limitation of dot notation: In some scenarios, bracket notation is the only option, such as when accessing properties when the property name is stored in a variable.
const person = {
name: 'Happy',
age: 35
};
// Dot notation
console.log(person.name); // Output: 'Happy'
// Bracket notation
console.log(person['name']); // Output: 'Happy'
// Dynamically assign property name to a variable
var propertyName = 'age';
// Bracket notation (necessary)
console.log(person[propertyName]); // Output: '35'
// Dot notation (won't work)
console.log(person.propertyName); // Output: undefined
Method | Description | Example |
---|---|---|
for...in loop | Iterates over the properties of an object. | for (let prop in person) { console.log(prop + ": " + person[prop]); } |
Object.keys() & forEach() | Gets the keys of an object as an array and iterates over them. | Object.keys(person).forEach(prop => console.log(prop + ": " + person[prop])); |
Object.values() & forEach() | Gets the values of an object as an array and iterates over them. | Object.values(person).forEach(value => console.log(value)); |
var person = {
name: "Alice",
age: 25
};
// 1. Using the in Operator
console.log("name" in person); // Output: true
console.log("city" in person); // Output: false
// 2. Using the hasOwnProperty() Method
console.log(person.hasOwnProperty("name")); // Output: true
console.log(person.hasOwnProperty("city")); // Output: false
// 3. Comparing with undefined
console.log(person.name !== undefined); // Output: true
console.log(person.city !== undefined); // Output: false
Method | Description | Example |
---|---|---|
Spread Syntax (...) | Creates a shallow copy of an object. | const clonedObjectSpread = { ...originalObject }; |
Object.assign() | Creates a shallow copy of an object. | const clonedObjectAssign = Object.assign({}, originalObject); |
JSON.parse() & JSON.stringify() | Creates a deep copy of an object, including nested objects and arrays. | const clonedObjectJSON = JSON.parse(JSON.stringify(originalObject)); |
Shallow Copy vs. Deep Copy in Nested Objects
Shallow Copy (using Object.assign()):
- Modifies the parent object's property value if the cloned object's property value is changed.
Deep Copy (using JSON.parse() and JSON.stringify()):
- Does not modify the parent object's property value when the cloned object's property value is changed.
Example:
const person = {
name: 'Happy',
age: 30,
address: {
city: 'Delhi',
country: 'India'
}
};
// Shallow copy using Object.assign()
const shallowCopy = Object.assign({}, person);
shallowCopy.address.city = 'Mumbai';
console.log(person.address.city); // Output: "Mumbai"
console.log(shallowCopy.address.city); // Output: "Mumbai"
// Deep copy using JSON.parse() and JSON.stringify()
const deepCopy = JSON.parse(JSON.stringify(person));
deepCopy.address.city = 'Bangalore';
console.log(person.address.city); // Output: "Delhi"
console.log(deepCopy.address.city); // Output: "Bangalore"
-
Definition: A Set object is a collection of unique values, meaning that duplicate values are not allowed.
-
Methods: Set objects provide methods for adding, deleting, and checking the existence of values in the set.
-
Removing Duplicates from Arrays: Sets can be used to remove duplicate values from arrays by creating a new Set from the array and then converting it back to an array.
// Creating a Set to store unique numbers
const uniqueNumbers = new Set();
uniqueNumbers.add(5);
uniqueNumbers.add(10);
uniqueNumbers.add(5); // Ignore duplicate values
console.log(uniqueNumbers); // Output: { 5, 10 }
// Check size
console.log(uniqueNumbers.size); // Output: 2
// Check element existence
console.log(uniqueNumbers.has(10)); // Output: true
// Delete element
uniqueNumbers.delete(10);
console.log(uniqueNumbers.size); // Output: 1
// Set can be used to remove duplicate values from arrays
let myArr = [1, 4, 3, 4];
let mySet = new Set(myArr);
let uniqueArray = [...mySet];
console.log(uniqueArray); // Output: [1, 4, 3]
The Map object is a collection of key-value pairs where each key can be of any type, and each value can also be of any type. A Map maintains the order of key-value pairs as they were inserted.
Example:
// Creating a Map to store person details
const personDetails = new Map();
personDetails.set("name", "Alice");
personDetails.set("age", 30);
console.log(personDetails.get("name")); // Output: "Alice"
console.log(personDetails.has("age")); // Output: true
personDetails.delete("age");
console.log(personDetails.size); // Output: 1
Feature | Map | JavaScript Object |
---|---|---|
Keys | Can be of any data type (strings, numbers, objects, functions, etc.). | Limited to strings and symbols. |
Key-Value Pair Order | Maintains insertion order. | No guaranteed order. |
Use Cases | Useful when keys are of different types or insertion order is important. | Useful when keys are strings or symbols and there are a simple set of properties. |