0% found this document useful (0 votes)
4 views12 pages

Week 2 - JS NOTE

This document covers key concepts in JavaScript, focusing on arrays and objects, including their creation, modification, and various methods such as map, filter, and reduce. It also explains the JavaScript Date object and its functionalities. Practical exercises are provided for beginners, intermediates, and advanced learners to reinforce the concepts learned.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

Week 2 - JS NOTE

This document covers key concepts in JavaScript, focusing on arrays and objects, including their creation, modification, and various methods such as map, filter, and reduce. It also explains the JavaScript Date object and its functionalities. Practical exercises are provided for beginners, intermediates, and advanced learners to reinforce the concepts learned.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Week 2: Arrays & Objects

 Understanding Arrays and Array Methods

 Deep Dive into ES6+ Array Methods (map, filter, reduce,

etc.)

 Understanding Objects and Their Properties

 Creating and Modifying Objects

 JavaScript Date Object and Its Methods


WEEK 2 – LESSON ONE
1. UNDERSTANDING ARRAYS AND ARRAY METHODS
What is an Array?
An array is a special type of variable that can hold multiple
values in a single variable.
Example: Creating an Array
let fruits = ["Apple", "Banana", "Orange"];
console.log(fruits); // ["Apple", "Banana", "Orange"]

Types of Arrays

 Number Array: let numbers = [10, 20, 30, 40];


 String Array: let names = ["John", "Jane", "Doe"];
 Mixed Data Array: let random = [10, "Hello", true, { name:
"John" }];
 Nested Arrays (Arrays inside Arrays):

let matrix = [[1, 2], [3, 4], [5, 6]];


console.log(matrix[1][0]); // 3

Accessing Elements in an Array


console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits.length); // 3

Modifying an Array
fruits[1] = "Grapes";
console.log(fruits); // ["Apple", "Grapes", "Orange"]

Adding and Removing Elements

 push() – Adds an element at the end


 pop() – Removes the last element
 unshift() – Adds an element at the beginning
 shift() – Removes the first element

let colors = ["Red", "Green"];


colors.push("Blue"); // ["Red", "Green", "Blue"]
colors.pop(); // ["Red", "Green"]
colors.unshift("Yellow"); // ["Yellow", "Red", "Green"]
colors.shift(); // ["Red", "Green"]

2. Deep Dive into ES6+ Array Methods

JavaScript provides many built-in methods for working with


arrays.

map() – Transforming Each Item

 Used to create a new array by modifying each element.

let numbers = [1, 2, 3, 4, 5];


let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

filter() – Selecting Specific Items

 Returns a new array with only the items that meet a


condition.

let ages = [12, 18, 22, 16, 25];


let adults = ages.filter(age => age >= 18);
console.log(adults); // [18, 22, 25]

reduce() – Accumulate a Single Value

 Used to reduce an array to a single value.


let prices = [10, 20, 30, 40];
let total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // 100

forEach() – Iterating Over an Array


 Runs a function for each item in an array (without creating a
new array).
let names = ["Alice", "Bob", "Charlie"];

names.forEach(name => console.log(`Hello, ${name}!`));

find() – Getting the First Matching Item

 Returns the first item that meets the condition.


let users = [

{ id: 1, name: "John" },

{ id: 2, name: "Alice" },

];

let user = users.find(user => user.id === 2);

console.log(user); // { id: 2, name: "Alice" }

some() & every() – Checking Conditions

 some() checks if at least one element passes a condition.


 every() checks if all elements pass a condition.

let numbers = [3, 5, 7, 9];


console.log(numbers.some(num => num > 5)); // true
console.log(numbers.every(num => num > 5)); // false

splice() – Adding and Removing Elements in an Array

What does it do?

 splice(start, deleteCount, item1, item2, ...) modifies the


original array by removing, replacing, or adding
elements.
array.splice(startIndex, deleteCount, newElement1, newElement2, ...);

Example 1: Removing Elements


let colors = ["Red", "Green", "Blue", "Yellow"];

colors.splice(1, 2); // Removes 2 elements starting from index 1


console.log(colors); // ["Red", "Yellow"]

Example 2: Adding Elements


let fruits = ["Apple", "Banana", "Orange"];
fruits.splice(1, 0, "Grapes", "Pineapple"); // Inserts without removing
console.log(fruits); // ["Apple", "Grapes", "Pineapple", "Banana", "Orange"]

Example 3: Replacing Elements


let numbers = [10, 20, 30, 40];
numbers.splice(2, 1, 25); // Replaces index 2 with 25
console.log(numbers); // [10, 20, 25, 40]
Use Cases

 Removing specific elements from an array


 Inserting new elements at any position
 Replacing elements in an array

slice() – Extracting a Portion of an Array

What does it do?

 slice(start, end) returns a new array with the extracted


elements, without modifying the original array.

Example 1: Extracting Elements


let animals = ["Lion", "Tiger", "Elephant", "Giraffe"];

let bigCats = animals.slice(0, 2); // Extracts from index 0 to 1

console.log(bigCats); // ["Lion", "Tiger"]

Example 2: Copying an Entire Array

let original = [1, 2, 3, 4];


let copy = original.slice(); // Creates a shallow copy
console.log(copy); // [1, 2, 3, 4]

Use Cases

 Getting a subset of an array


 Copying an array without modifying the original
 Breaking large data into chunks

reverse() – Reversing the Order of Elements

What does it do?

 reverse() modifies the array by reversing the order of


elements.

let numbers = [1, 2, 3, 4, 5];


numbers.reverse();
console.log(numbers); // [5, 4, 3, 2, 1]
Use Cases

 Reversing a list (e.g., messages, events)


 Implementing palindrome checks

🔴 Warning: reverse() modifies the original array. Use


slice().reverse() to avoid modifying the original array.
let arr = [1, 2, 3, 4];

let reversedCopy = arr.slice().reverse();

console.log(reversedCopy); // [4, 3, 2, 1]

console.log(arr); // [1, 2, 3, 4] (original array remains unchanged)

concat() – Merging Two or More Arrays

What does it do?

 concat() returns a new array by merging two or more


arrays.

let arr1 = [1, 2, 3];


let arr2 = [4, 5, 6];
let combined = arr1.concat(arr2);
console.log(combined); // [1, 2, 3, 4, 5, 6]

Example: Concatenating Multiple Arrays


let letters = ["A", "B", "C"];
let numbers = [1, 2, 3];
let symbols = ["@", "#", "$"];
let combinedArray = letters.concat(numbers, symbols);
console.log(combinedArray); // ["A", "B", "C", 1, 2, 3, "@", "#", "$"]
Use Cases

 Merging multiple datasets


 Combining lists of elements
 Avoiding the mutation of original arrays

sort() – Sorting an Array

What does it do?

 sort() arranges the elements of an array in ascending


order (default) or a custom order.
 By default, sort() converts elements to strings before
sorting. This can cause unexpected behavior with numbers.

Example 1: Sorting Strings


let names = ["Alice", "Bob", "Charlie"];
names.sort();
console.log(names); // ["Alice", "Bob", "Charlie"]

Example 2: Sorting Numbers (Incorrect Way)


let numbers = [100, 50, 25, 10, 5, 1];
numbers.sort();
console.log(numbers); // [1, 10, 100, 25, 5, 50] ❌ (Incorrect!)

Example 3: Sorting Numbers (Correct Way)


numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 5, 10, 25, 50, 100] ✅

Example 4: Sorting in Descending Order

let scores = [80, 95, 60, 70];


scores.sort((a, b) => b - a);
console.log(scores); // [95, 80, 70, 60]
Use Cases

 Alphabetizing a list of names


 Sorting numbers correctly using a comparator function
 Ordering products by price

Hands-On Exercises

Beginner Level

1. Create an array of five different cities.


2. Use splice() to remove the second city and replace it with a
new one.
3. Use slice() to get the last three cities.

Intermediate Level

1. Create an array of numbers [10, 5, 8, 1, 7].


2. Sort the numbers in ascending order.
3. Reverse the sorted array.
4. Use concat() to add more numbers [12, 15, 18].

Advanced Level

1. Create an array of objects representing students with name


and score.
2. Use sort() to order students by their score in descending
order.
3. Use map() to create a new array of student names only.
Use Cases
 Storing a list of items (e.g., names of students, product lists,
etc)
 Iterating over data to process each item
 Grouping related information

Best Practices
 Always use const when declaring arrays unless you need to
reassign them.
 Use meaningful names (students instead of arr).
 Use array methods instead of loops where possible.

Practical Exercise
 Create an array called colors with at least five color names
 Print the third color in the array.
 Add a new color at the end of the array.
 Remove the first color from the array.

3. UNDERSTANDING OBJECTS AND THEIR PROPERTIES

What is an Object?

An object is a collection of key-value pairs.

Creating an Object
let person = {
name: "John",
age: 25,
isStudent: false
};
console.log(person.name); // John
Accessing & Modifying Properties
console.log(person["age"]); // 25
person.age = 30;
console.log(person.age); // 30

4. Creating and Modifying Objects

Adding and Removing Properties


let user = { name: "Alice" };
user.age = 30; // Add property
delete user.age; // Remove property
console.log(user);

Object Methods

 Objects can have functions inside them.


let student = {
name: "Sarah",
greet: function() {
console.log("Hello, " + this.name);
}
};
student.greet(); // Hello, Sarah

Looping Through an Object


let car = { brand: "Toyota", model: "Corolla", year: 2022 };
for (let key in car) {
console.log(`${key}: ${car[key]}`);
}

5. JavaScript Date Object and Its Methods

Creating a Date Object


let today = new Date();

console.log(today);

Getting Date Components


console.log(today.getFullYear()); // Current year
console.log(today.getMonth()); // Current month (0-based)
console.log(today.getDate()); // Current day

Formatting Dates
let options = { year: "numeric", month: "long", day: "numeric" };
console.log(new Date().toLocaleDateString("en-US", options));

Use Cases of the Date Object

 Displaying timestamps
 Scheduling tasks
 Measuring execution time

Practical Exercises

Beginner Exercises

1. Create an array of your top 5 favorite foods.


2. Use map() to make each food name uppercase.
3. Use filter() to find food names longer than 5 letters.

Intermediate Exercises

1. Create an object book with properties title, author, and year.


2. Add a method getSummary that prints a summary of the
book.
3. Use Object.keys(book) to print all property names.

Advanced Challenge

 Create an array of objects where each object represents a


person with name, age, and gender.
 Use filter() to get all males.
 Use map() to return an array of names.
 Use reduce() to calculate the average age.

You might also like