This document explains Objects, Array of Objects, important Array Methods, Local Storage, and the this
keyword in JavaScript with definitions and examples.
- An Object is a collection of key-value pairs.
- It helps us store related data together.
- Objects are useful when you want a single variable to hold multiple related values.
const student = {
name: "Ali",
age: 20,
isEnrolled: true,
courses: ["Math", "Science", "English"], // Array inside object
address: { city: "Karachi", country: "Pakistan" }, // Object inside object
greet: function() { // Function inside object
return `Hello, my name is ${this.name}`;
}
};
console.log(student.name); // Ali
console.log(student.courses[1]); // Science
console.log(student.address.city); // Karachi
console.log(student.greet()); // Hello, my name is Ali
π Inside an object, we can store:
- String
- Number
- Boolean
- Array
- Another Object
- Function
- An Array of Objects is used when we want to store multiple objects together in a list.
- Very useful in real-world apps like users, products, students, tasks.
const students = [
{ id: 1, name: "Ali", age: 20 },
{ id: 2, name: "Sara", age: 22 },
{ id: 3, name: "Ahmed", age: 19 }
];
console.log(students[0].name); // Ali
console.log(students[2].age); // 19
- Definition: Executes a function once for each array element.
- Use Case: Iterating through arrays (does not return a new array).
const numbers = [1, 2, 3, 4];
numbers.forEach(num => console.log(num * 2));
// Output: 2, 4, 6, 8
With Array of Objects:
students.forEach(student => {
console.log(student.name);
});
// Output: Ali, Sara, Ahmed
- Definition: Creates a new array by applying a function to each element.
- Use Case: When you want to transform data.
const numbers = [1, 2, 3];
const squares = numbers.map(num => num * num);
console.log(squares); // [1, 4, 9]
With Array of Objects:
const names = students.map(s => s.name);
console.log(names); // ["Ali", "Sara", "Ahmed"]
- Definition: Creates a new array with elements that pass a condition.
- Use Case: Filtering data.
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
With Array of Objects:
const adults = students.filter(s => s.age > 20);
console.log(adults);
// [{ id: 2, name: "Sara", age: 22 }]
- Definition: Returns the first element that matches the condition.
- Use Case: When you only need one specific item.
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 2
With Array of Objects:
const studentSara = students.find(s => s.name === "Sara");
console.log(studentSara);
// { id: 2, name: "Sara", age: 22 }
- Definition: Reduces an array to a single value (sum, average, max, etc.).
- Use Case: Calculating totals or combining values.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0);
console.log(sum); // 10
π Explanation:
accumulator
: stores the result from previous steps.currentValue
: current element being processed.0
: initial value (important to avoid errors if the array is empty).
π Step by Step:
- Initial:
acc = 0
- First iteration:
0 + 1 = 1
- Second:
1 + 2 = 3
- Third:
3 + 3 = 6
- Fourth:
6 + 4 = 10
With Array of Objects:
const totalAge = students.reduce((acc, s) => acc + s.age, 0);
console.log(totalAge); // 61
-
Definition: Local Storage allows you to store data in the browser permanently (until manually cleared).
-
Why Use It?
- Data does not disappear after page refresh.
- Useful for saving user preferences, cart items, login info, etc.
// Save data
localStorage.setItem("username", "Ali");
// Get data
console.log(localStorage.getItem("username")); // Ali
// Remove data
localStorage.removeItem("username");
// Clear all
localStorage.clear();
// Convert object/array into string
localStorage.setItem("students", JSON.stringify(students));
// Get back data
const savedStudents = JSON.parse(localStorage.getItem("students"));
console.log(savedStudents);
// Same array of students restored
π Methods:
setItem(key, value)
β Store datagetItem(key)
β Retrieve dataremoveItem(key)
β Remove specific dataclear()
β Remove all dataJSON.stringify()
β Convert object/array β stringJSON.parse()
β Convert string β object/array
- Definition:
this
refers to the object that is currently executing the function. - It allows objects to access their own properties and methods.
const person = {
name: "Ali",
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.greet()); // Hello, my name is Ali
console.log(this);
// In browser β Window object
function showThis() {
console.log(this);
}
showThis();
// In strict mode β undefined
// In normal mode β Window object
π Summary:
- In an object method,
this
refers to the object itself. - In a regular function,
this
refers to global object (window
in browsers). - In strict mode, standalone functions return
undefined
.
- Objects: Store related data together.
- Array of Objects: Manage lists of objects.
- forEach: Loop through items.
- map: Transform data.
- filter: Extract data.
- find: Get one item.
- reduce: Combine into a single value.
- Local Storage: Save data in browser (with
JSON.stringify
&JSON.parse
). - this keyword: Refers to current object executing the function.
π With these concepts, you can build real-world apps like:
- E-commerce carts
- Student management systems
- Todo apps
- Weather apps