Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

JavaScript Array Methods

Learn how to add, remove, search, transform, filter and process array elements using commonly used JavaScript array methods.

push() pop() map() filter() find() reduce() sort()

1. What Is an Array?

An array is a JavaScript data structure used to store multiple values in a single variable. These values are arranged in an ordered collection and accessed using their index.

For example, a training institute may store several course names in one array instead of creating a separate variable for every course.

JavaScript - Example 1
let courses = ["Java", "Python", ".NET", "React"];

console.log(courses);
console.log(courses[0]);
console.log(courses[2]);

Expected Output

["Java", "Python", ".NET", "React"]
Java
.NET

Understanding Array Indexes

Index Value
0Java
1Python
2.NET
3React
Remember: JavaScript array indexes start from 0, not 1. The first element is at index 0, and the last element is at index array.length - 1.

2. Why Do We Use Array Methods?

Array methods provide built-in operations for working with collections. They help us modify arrays, search for values, transform data and calculate results without writing every operation manually.

  • Add or remove elements from an array.
  • Check whether a value exists.
  • Create a new array from existing elements.
  • Filter elements according to a condition.
  • Calculate totals and other aggregate values.
  • Sort and rearrange elements.

3. How Do Array Methods Work?

An array method operates on an array. Depending on the method, it can modify the original array, return a value, or create a new array.

Step 1: Input

Original Array

[10, 20, 30, 40]
↓
Step 2: Operation

Apply an Array Method

map(), filter(), reduce()
↓
Step 3: Result

Use the Returned Value

[20, 40, 60, 80]
Important: Not every array method behaves the same way. For example, push() modifies the original array, while map() returns a new array.

4. push() Method

The push() method adds one or more elements to the end of an array. It modifies the original array and returns its new length.

JavaScript - Example 2
let fruits = ["Apple", "Banana"];

let newLength = fruits.push("Mango");

console.log(fruits);
console.log(newLength);

Expected Output

["Apple", "Banana", "Mango"]
3

The new fruit is added at the end of the array. The returned value 3 represents the array's new length.

5. pop() Method

The pop() method removes the last element from an array and returns the removed element. It modifies the original array.

JavaScript - Example 3
let fruits = ["Apple", "Banana", "Mango"];

let removedFruit = fruits.pop();

console.log(fruits);
console.log(removedFruit);

Expected Output

["Apple", "Banana"]
Mango

The last element, "Mango", is removed from the array and stored in removedFruit.

6. shift() and unshift() Methods

shift() Method

The shift() method removes the first element of an array and returns the removed element.

JavaScript - Example 4
let numbers = [10, 20, 30];

let removed = numbers.shift();

console.log(numbers);
console.log(removed);

Expected Output

[20, 30]
10

unshift() Method

The unshift() method adds one or more elements to the beginning of an array and returns the new length.

JavaScript - Example 5
let numbers = [20, 30];

let newLength = numbers.unshift(10);

console.log(numbers);
console.log(newLength);

Expected Output

[10, 20, 30]
3

7. includes() and indexOf() Methods

includes()

The includes() method checks whether an array contains a specified value. It returns true or false.

JavaScript - Example 6
let courses = ["Java", "Python", ".NET"];

console.log(courses.includes("Python"));
console.log(courses.includes("PHP"));

Expected Output

true
false

indexOf()

The indexOf() method returns the index of the first matching value. If the value is not found, it returns -1.

JavaScript - Example 7
let courses = ["Java", "Python", ".NET"];

console.log(courses.indexOf("Python"));
console.log(courses.indexOf("PHP"));

Expected Output

1
-1

8. slice() Method

The slice() method returns a shallow copy of a selected portion of an array. It does not modify the original array.

The ending index is excluded from the returned portion.

JavaScript - Example 8
let numbers = [10, 20, 30, 40, 50];

let result = numbers.slice(1, 4);

console.log(result);
console.log(numbers);

Expected Output

[20, 30, 40]
[10, 20, 30, 40, 50]

The elements at indexes 1, 2 and 3 are included. Index 4 is excluded. The original array remains unchanged.

9. splice() Method

The splice() method can remove, replace or insert elements at a specified position. Unlike slice(), it modifies the original array.

JavaScript - Example 9
let fruits = ["Apple", "Banana", "Mango", "Orange"];

let removed = fruits.splice(1, 2);

console.log(fruits);
console.log(removed);

Expected Output

["Apple", "Orange"]
["Banana", "Mango"]

Insert an Element Using splice()

JavaScript - Example 10
let fruits = ["Apple", "Mango"];

fruits.splice(1, 0, "Banana");

console.log(fruits);

Expected Output

["Apple", "Banana", "Mango"]

In splice(1, 0, "Banana"), the first argument specifies the starting index, the second specifies how many elements to remove, and the third supplies the new element.

10. map() Method

The map() method creates a new array by applying a callback function to every element of the original array.

It is useful when we want to transform every element, such as multiplying each number by two or extracting a property from every object.

JavaScript - Example 11
let numbers = [1, 2, 3, 4];

let result = numbers.map(number => number * 2);

console.log(result);
console.log(numbers);

Expected Output

[2, 4, 6, 8]
[1, 2, 3, 4]

How map() Works

Original Value Operation New Value
11 × 22
22 × 24
33 × 26
44 × 28
Remember: map() returns a new array. The original array is not changed by this example.

11. filter() Method

The filter() method creates a new array containing only those elements that satisfy a condition.

JavaScript - Example 12
let numbers = [10, 15, 20, 25, 30];

let result = numbers.filter(number => number > 20);

console.log(result);

Expected Output

[25, 30]

The callback checks every number. Only numbers greater than 20 are included in the returned array.

Practical Example: Filter Passed Students

JavaScript - Example 13
let marks = [35, 75, 28, 90, 45];

let passed = marks.filter(mark => mark >= 40);

console.log(passed);

Expected Output

[75, 90, 45]

12. find() and findIndex() Methods

find()

The find() method returns the first element that satisfies the specified condition. If no element matches, it returns undefined.

JavaScript - Example 14
let numbers = [10, 25, 30, 45];

let result = numbers.find(number => number > 20);

console.log(result);

Expected Output

25

findIndex()

The findIndex() method returns the index of the first element that satisfies the condition. If no element matches, it returns -1.

JavaScript - Example 15
let numbers = [10, 25, 30, 45];

let result = numbers.findIndex(number => number > 20);

console.log(result);

Expected Output

1

13. reduce() Method

The reduce() method processes array elements and combines them into a single accumulated result. It is commonly used to calculate totals, products and other aggregate values.

JavaScript - Example 16
let numbers = [10, 20, 30, 40];

let total = numbers.reduce(
    (sum, number) => sum + number,
    0
);

console.log(total);

Expected Output

100

Understanding reduce()

Current Number Previous Total New Total
10010
201030
303060
4060100

The initial accumulator value is 0. The callback adds each number to the running total, and the final result is 100.

14. forEach() Method

The forEach() method executes a callback function for each element of an array. It is useful when we want to perform an action for every item, such as displaying each value.

JavaScript - Example 17
let courses = ["Java", "Python", ".NET"];

courses.forEach(course => {
    console.log(course);
});

Expected Output

Java
Python
.NET
Important: forEach() returns undefined. If you need a new transformed array, use map() instead.

15. sort() and reverse() Methods

sort()

The sort() method sorts an array in place. By default, it sorts elements as strings, so a numeric comparator should be used when sorting numbers numerically.

JavaScript - Example 18
let numbers = [40, 10, 30, 20];

numbers.sort((a, b) => a - b);

console.log(numbers);

Expected Output

[10, 20, 30, 40]

Descending Order

JavaScript - Example 19
let numbers = [40, 10, 30, 20];

numbers.sort((a, b) => b - a);

console.log(numbers);

Expected Output

[40, 30, 20, 10]

reverse()

The reverse() method reverses the order of elements in the original array.

JavaScript - Example 20
let numbers = [10, 20, 30, 40];

numbers.reverse();

console.log(numbers);

Expected Output

[40, 30, 20, 10]

16. Array Methods Comparison

Method Purpose Changes Original Array? Returns
push() Add at the end Yes New length
pop() Remove from the end Yes Removed element
shift() Remove from the beginning Yes Removed element
unshift() Add at the beginning Yes New length
slice() Copy a portion No New array
splice() Insert, remove or replace Yes Array of removed elements
map() Transform elements No, in normal use New array
filter() Select matching elements No New array
find() Find first matching element No Element or undefined
reduce() Combine values No, in normal use Accumulated result
forEach() Perform an action for each item Depends on callback actions undefined
sort() Sort elements Yes Same array, sorted
reverse() Reverse element order Yes Same array, reversed

17. map(), filter() and reduce() Diagram

These three methods are especially useful when processing arrays. Each one has a different purpose.

Input Array

Original Values

[10, 20, 30, 40]
↓
map(number => number * 2)

Transforms every element.

[20, 40, 60, 80]
↓
filter(number => number > 40)

Keeps only matching elements.

[60, 80]
↓
reduce((sum, number) => sum + number, 0)

Combines elements into one result.

140
Learning Tip: Use map() to transform, filter() to select, and reduce() to calculate a combined result.

18. Practical Example: Process Course Fees

Suppose a training institute has course fees stored in an array. We want to increase each fee by 10%, select fees greater than ₹20,000, and calculate the total of the selected fees.

JavaScript - Practical Example
let fees = [15000, 20000, 25000, 30000];

let increasedFees = fees.map(fee => fee * 1.10);

let selectedFees = increasedFees.filter(fee => fee > 22000);

let total = selectedFees.reduce(
    (sum, fee) => sum + fee,
    0
);

console.log("Original Fees:", fees);
console.log("Increased Fees:", increasedFees);
console.log("Selected Fees:", selectedFees);
console.log("Total Selected Fees:", total);

Expected Output

Original Fees: [15000, 20000, 25000, 30000]
Increased Fees: [16500, 22000, 27500, 33000]
Selected Fees: [27500, 33000]
Total Selected Fees: 60500

Explanation

  1. map() increases every fee by 10%.
  2. filter() selects the increased fees greater than 22,000.
  3. reduce() adds the selected fees to calculate the total.
  4. The original fees array remains unchanged.

19. Common Mistakes

Mistake Correct Understanding
Assuming the first index is 1. Array indexes start at 0.
Assuming slice() modifies the array. slice() returns a new array.
Assuming splice() leaves the array unchanged. splice() modifies the original array.
Using map() when only a matching value is needed. Use find() or filter(), depending on the requirement.
Using default sort() for numeric order. Use a numeric comparator such as (a, b) => a - b.
Expecting forEach() to return a new array. Use map() when a transformed array is needed.

20. Practice Tasks

Task 1: Add and Remove Elements

Create an array of three fruits.

  • Add one fruit using push().
  • Remove the last fruit using pop().
  • Display the final array.
Expected Result:
["Apple", "Banana", "Mango"]

Task 2: Filter Even Numbers

Given the array [10, 15, 20, 25, 30, 35], use filter() to select only even numbers.

Expected Output:
[10, 20, 30]

Task 3: Calculate Total Prices

Given [100, 200, 300, 400], use reduce() to calculate the total.

Expected Output:
1000

Task 4: Convert Names to Uppercase

Given ["samadhan", "pradnya", "student"], use map() and toUpperCase() to create a new array of uppercase names.

Expected Output:
["SAMADHAN", "PRADNYA", "STUDENT"]

Summary

JavaScript array methods make it easier to manage and process collections of values.

  • push() adds elements at the end.
  • pop() removes the last element.
  • shift() removes the first element.
  • unshift() adds elements at the beginning.
  • includes() checks whether a value exists.
  • slice() copies a portion without changing the original array.
  • splice() inserts, removes or replaces elements in the original array.
  • map() transforms elements into a new array.
  • filter() selects elements that match a condition.
  • find() returns the first matching element.
  • reduce() combines values into a single result.
  • forEach() performs an action for each element.
  • sort() sorts elements, and reverse() reverses their order.