Skip to content

SHAHBAZ-SHEIKH/javaScriptTopic

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 

Repository files navigation

πŸ“˜ JavaScript Concepts: Objects, Arrays, Reduce, LocalStorage & this Keyword

This document explains Objects, Array of Objects, important Array Methods, Local Storage, and the this keyword in JavaScript with definitions and examples.


πŸ”Ή What is an Object?

  • 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.

βœ… Example:

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

πŸ”Ή Array of Objects

  • 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.

βœ… Example:

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

πŸ”Ή Array Methods

1️⃣ forEach()

  • 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

2️⃣ map()

  • 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"]

3️⃣ filter()

  • 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 }]

4️⃣ find()

  • 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 }

5️⃣ reduce()

  • Definition: Reduces an array to a single value (sum, average, max, etc.).
  • Use Case: Calculating totals or combining values.

How it works:

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

πŸ”Ή Local Storage

  • 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.

⚠️ Important: Local Storage only stores strings. If you want to store objects or arrays, you must convert them into strings.

βœ… Example:

// Save data
localStorage.setItem("username", "Ali");

// Get data
console.log(localStorage.getItem("username")); // Ali

// Remove data
localStorage.removeItem("username");

// Clear all
localStorage.clear();

Storing Objects/Arrays

// 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 data
  • getItem(key) β†’ Retrieve data
  • removeItem(key) β†’ Remove specific data
  • clear() β†’ Remove all data
  • JSON.stringify() β†’ Convert object/array β†’ string
  • JSON.parse() β†’ Convert string β†’ object/array

πŸ”Ή The this Keyword

  • Definition: this refers to the object that is currently executing the function.
  • It allows objects to access their own properties and methods.

βœ… Example 1 (Inside Object):

const person = {
  name: "Ali",
  greet: function() {
    return `Hello, my name is ${this.name}`;
  }
};

console.log(person.greet()); // Hello, my name is Ali

βœ… Example 2 (Global Context):

console.log(this); 
// In browser β†’ Window object

βœ… Example 3 (Function Context):

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.

🎯 Summary

  • 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

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published