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 Loops and Iteration

Learn how to execute a block of code repeatedly using JavaScript loops. Understand for, while, do-while, for...of, for...in, break, and continue with detailed examples and expected outputs.

1. What Are Loops in JavaScript?

A loop is a programming structure that executes a block of code repeatedly while a condition is satisfied or while items remain to be processed.

For example, if we want to display numbers from 1 to 100, we do not need to write 100 separate console.log() statements. A loop can perform the same task using a few lines of code.

JavaScript provides several types of loops:

  • for loop
  • while loop
  • do...while loop
  • for...of loop
  • for...in loop
Remember: Always ensure that a loop can eventually finish. If its condition never becomes false and there is no exit statement, it may create an infinite loop.

2. How Does a Loop Work?

A typical loop initializes a variable, checks a condition, executes the loop body, updates the variable, and checks the condition again.

Start
↓
Initialize Variable

let i = 1

↓
Check Condition

i <= 5

True

Execute loop body and update variable

False

Exit the loop

When the condition is true, execution returns to the condition check after the loop body and update.

3. The for Loop

A for loop is useful when the number of iterations is known or when a variable controls how many times the code runs.

Syntax

JavaScript
for (initialization; condition; update) {
    // Code to execute repeatedly
}

The three parts of a standard for loop are:

  • Initialization: Sets the starting value.
  • Condition: Determines whether the next iteration runs.
  • Update: Changes the loop variable after each iteration.

Example: Print Numbers from 1 to 5

JavaScript
for (let i = 1; i <= 5; i++) {
    console.log(i);
}

Output

Output
1
2
3
4
5

Explanation: The variable i starts at 1. The loop continues while i <= 5. After every iteration, i++ increases the value by one.

4. The while Loop

A while loop checks its condition before executing the loop body. If the condition is false at the beginning, the body does not execute.

Syntax

JavaScript
while (condition) {
    // Code to execute
}

Example: Print Even Numbers

JavaScript
let number = 2;

while (number <= 10) {
    console.log(number);
    number += 2;
}

Output

Output
2
4
6
8
10

Explanation: The loop starts with 2 and increases the number by 2 after each iteration. When the number becomes 12, the condition becomes false and the loop stops.

5. The do...while Loop

A do...while loop executes the loop body first and checks the condition afterward. Therefore, the body executes at least once, even if the condition is initially false.

Syntax

JavaScript
do {
    // Code to execute
} while (condition);

Example

JavaScript
let i = 1;

do {
    console.log(i);
    i++;
} while (i <= 3);

Output

Output
1
2
3

Important Difference

JavaScript
let number = 10;

do {
    console.log("Executed once");
} while (number < 5);

Output

Output
Executed once

The condition is false, but the message is still displayed once because a do...while loop checks its condition after executing the body.

6. Difference Between for, while and do...while

Feature for while do...while
Condition checked Before each iteration Before each iteration After each iteration
Minimum executions Zero Zero One
Typical use Counter-controlled repetition Repeat while a condition is true Execute once before checking

7. The for...of Loop

The for...of loop iterates over the values of an iterable, such as an array or string. It is particularly useful when we want to process each item in a collection.

Example: Display Course Names

JavaScript
let courses = ["JavaScript", "Node.js", "React"];

for (let course of courses) {
    console.log(course);
}

Output

Output
JavaScript
Node.js
React

Explanation: In each iteration, the variable course receives the next value from the array.

8. The for...in Loop

The for...in loop iterates over enumerable property keys of an object. It is useful when you need to inspect an object's property names.

Example: Display Student Details

JavaScript
let student = {
    name: "Samadhan",
    age: 22,
    course: "JavaScript"
};

for (let key in student) {
    console.log(key + ": " + student[key]);
}

Output

Output
name: Samadhan
age: 22
course: JavaScript

Explanation: The variable key receives each property name. The expression student[key] accesses the value associated with that property.

Important: Prefer for...of for iterating over array values. A for...in loop iterates over property keys and may also include inherited enumerable properties.

9. Choosing the Right Loop

Different loops are useful for different requirements. This diagram summarizes when to consider each loop type.

What Do You Need to Repeat?
Known Counter

Use for

Condition-Based Repetition

Use while

Run Body at Least Once

Use do...while

Collection Values

Use for...of

Object Property Keys

Use for...in

10. The break Statement

The break statement immediately terminates the nearest enclosing loop. Program execution then continues after that loop.

Example

JavaScript
for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        break;
    }

    console.log(i);
}

Output

Output
1
2
3
4

When i becomes 5, the condition is true and break terminates the loop. The number 5 is not printed.

11. The continue Statement

The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration.

Example: Skip Number 3

JavaScript
for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        continue;
    }

    console.log(i);
}

Output

Output
1
2
4
5

When i equals 3, the current iteration is skipped. The loop continues with the next value, 4.

12. Practical Program: Calculate Total Marks

Let us use a loop to calculate the total marks obtained by a student in three subjects.

Step 1: Create a File

Create a file named totalmarks.js.

Step 2: Write the Program

JavaScript
let marks = [80, 75, 90];
let total = 0;

for (let i = 0; i < marks.length; i++) {
    total += marks[i];
}

let average = total / marks.length;

console.log("Total Marks:", total);
console.log("Average Marks:", average);

Step 3: Run the Program

Terminal
node totalmarks.js

Step 4: Expected Output

Output
Total Marks: 245
Average Marks: 81.66666666666667

Explanation: The loop visits each element of the marks array and adds it to total. The program then divides the total by the number of subjects to calculate the average.

13. Common Mistakes

Mistake Explanation Solution
Infinite loop The condition never becomes false. Check the condition and update the loop variable correctly.
Off-by-one error The loop executes one time too many or too few. Check the starting value and boundary condition.
Forgetting to update A while loop may never reach its exit condition. Update the variable when required.
Using for...in for array values It iterates over property keys, not directly over values. Use for...of when processing array values.
Confusing break and continue Break exits the loop; continue skips an iteration. Use the statement that matches the requirement.

14. Practice Task

Number and Marks Processing

Create a JavaScript program that performs the following tasks:

  • Use a for loop to print numbers from 1 to 10.
  • Use a while loop to print even numbers from 2 to 20.
  • Use a do...while loop to display a message at least once.
  • Use for...of to display an array of course names.
  • Use for...in to display the properties of a student object.
  • Use break to stop a loop at a specified number.
  • Use continue to skip a particular number.
  • Calculate the total and average of an array of marks.
Challenge: Write a program that checks numbers from 1 to 50 and displays only those numbers that are divisible by both 3 and 5.

Important Points

  • Use for when a counter controls repetition.
  • Use while when repetition depends on a condition.
  • A do...while loop executes at least once.
  • Use for...of to iterate over iterable values.
  • Use for...in to iterate over enumerable object property keys.
  • break terminates the nearest enclosing loop.
  • continue skips the current iteration and proceeds to the next one.

Summary

JavaScript loops allow us to execute code repeatedly without writing the same statements multiple times. The for, while, and do...while loops support different repetition patterns. The for...of loop processes iterable values, while for...in iterates over enumerable property keys. The break and continue statements provide additional control over loop execution. These concepts are useful for processing arrays, calculating totals, validating data, and automating repetitive tasks.