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 If, Else If, Else and Switch

Learn how to control program execution using conditional statements in JavaScript. Understand if, if-else, else-if ladders, nested if, and switch statements with practical examples and outputs.

1. What Are Conditional Statements?

Conditional statements allow a program to make decisions based on whether a condition is true or false.

For example, a student result program can check marks and display whether the student has passed or failed. Similarly, an application can check a user's role before allowing a particular operation.

JavaScript provides the following conditional statements:

  • if — executes code when a condition is true.
  • if-else — chooses between two alternatives.
  • else if — checks multiple conditions in sequence.
  • Nested if — places one condition inside another.
  • switch — selects a case based on an expression's value.
Remember: JavaScript evaluates conditions using truthiness. A condition can evaluate to a truthy or falsy value, and the selected block executes accordingly.

2. The if Statement

The if statement executes a block of code only when its condition evaluates to true.

Syntax

JavaScript
if (condition) {
    // Code executes when the condition is true
}

Example: Check Passing Marks

JavaScript
let marks = 75;

if (marks >= 40) {
    console.log("Student passed");
}

console.log("Program completed");

Output

Output
Student passed
Program completed

Explanation: The condition marks >= 40 is true because marks are 75. Therefore, the message Student passed is displayed. The program then continues to the next statement.

When the Condition Is False

JavaScript
let marks = 25;

if (marks >= 40) {
    console.log("Student passed");
}

console.log("Program completed");

Output

Output
Program completed

Since the condition is false, the message inside the if block is skipped.

3. The if-else Statement

The if-else statement provides two alternatives. If the condition is true, the if block executes. Otherwise, the else block executes.

Syntax

JavaScript
if (condition) {
    // Executes when true
} else {
    // Executes when false
}

Example: Pass or Fail

JavaScript
let marks = 35;

if (marks >= 40) {
    console.log("Pass");
} else {
    console.log("Fail");
}

Output

Output
Fail

The marks are 35, which is below 40. Therefore, the condition is false and the else block executes.

4. if-else Decision Flowchart

This simplified flowchart shows how JavaScript chooses a block according to the result of a condition.

Start
↓
Check Condition

marks >= 40

TRUE

Display Pass

FALSE

Display Fail

↓
End

5. The else-if Ladder

An else if ladder is used when multiple conditions must be checked in sequence. JavaScript evaluates conditions from top to bottom and executes the first matching block.

Syntax

JavaScript
if (condition1) {
    // First condition
} else if (condition2) {
    // Second condition
} else if (condition3) {
    // Third condition
} else {
    // No previous condition matched
}

Example: Student Grades

Assume the following grading rules for this example:

Marks Grade
90 and above A
75 to 89 B
60 to 74 C
40 to 59 D
Below 40 Fail
JavaScript
let marks = 82;

if (marks >= 90) {
    console.log("Grade A");
} else if (marks >= 75) {
    console.log("Grade B");
} else if (marks >= 60) {
    console.log("Grade C");
} else if (marks >= 40) {
    console.log("Grade D");
} else {
    console.log("Fail");
}

Output

Output
Grade B

Explanation: The marks are 82. The first condition is false, but marks >= 75 is true. JavaScript displays Grade B and skips the remaining branches.

Important: Check conditions in the correct order. If a broad condition such as marks >= 40 is placed first, higher grades may never be reached.

6. Nested if Statements

A nested if statement is an if statement placed inside another conditional block. It is useful when a second condition should be checked only after the first condition succeeds.

Example: Course Admission

JavaScript
let marks = 75;
let documentsSubmitted = true;

if (marks >= 60) {
    if (documentsSubmitted) {
        console.log("Admission eligible");
    } else {
        console.log("Submit your documents");
    }
} else {
    console.log("Minimum marks requirement not met");
}

Output

Output
Admission eligible

The marks requirement is satisfied, so JavaScript checks the second condition. Since the documents are also submitted, the program displays Admission eligible.

7. The switch Statement

The switch statement selects a case based on the value of an expression. It can be useful when comparing one expression against several possible values.

Syntax

JavaScript
switch (expression) {
    case value1:
        // Statements
        break;

    case value2:
        // Statements
        break;

    default:
        // No matching case
}

Example: Day Selection

JavaScript
let day = 3;

switch (day) {
    case 1:
        console.log("Monday");
        break;

    case 2:
        console.log("Tuesday");
        break;

    case 3:
        console.log("Wednesday");
        break;

    case 4:
        console.log("Thursday");
        break;

    default:
        console.log("Invalid day");
}

Output

Output
Wednesday

Explanation: The value of day is 3, so the matching case 3 executes. The break statement exits the switch block after displaying the message.

Remember: A switch statement normally compares case values using strict equality. The default block executes when no case matches. Without a break, execution can continue into subsequent cases.

8. Conditional Statements Decision Diagram

Choose the conditional statement based on the number of alternatives and the type of decision your program needs to make.

Need to Make a Decision?
↓
One Condition

Use if

Two Alternatives

Use if-else

Multiple Conditions

Use else if

Multiple Exact Values

Consider switch

9. Practical Program: Simple Calculator

Let us create a simple calculator that performs an operation based on a selected operator. This example uses a switch statement.

Step 1: Create a File

Create a file named calculator.js.

Step 2: Write the Program

JavaScript
let a = 20;
let b = 5;
let operator = "*";

switch (operator) {
    case "+":
        console.log("Result:", a + b);
        break;

    case "-":
        console.log("Result:", a - b);
        break;

    case "*":
        console.log("Result:", a * b);
        break;

    case "/":
        if (b !== 0) {
            console.log("Result:", a / b);
        } else {
            console.log("Cannot divide by zero");
        }
        break;

    default:
        console.log("Invalid operator");
}

Step 3: Run the Program

Terminal
node calculator.js

Step 4: Expected Output

Output
Result: 100

Explanation: The variable operator contains "*", so the multiplication case executes. The result is 20 * 5 = 100.

10. Common Mistakes

Mistake Explanation Solution
Using = instead of a comparison = assigns a value rather than checking equality. Use an appropriate comparison operator.
Incorrect condition order A broad condition can match before a more specific one. Place conditions in the intended order.
Missing braces Only the next statement belongs to an unbraced conditional. Use braces to make blocks clear.
Missing break in switch Execution may continue into later cases. Add break when fall-through is not intended.
Ignoring the default case Unexpected values may not be handled. Use default when a fallback is appropriate.

11. Practice Task

Student Grade Calculator

Create a JavaScript program that:

  • Stores marks in a variable.
  • Uses if to check whether marks are valid.
  • Uses an else if ladder to assign a grade.
  • Displays Pass or Fail using a conditional statement.
  • Uses a switch statement to display a message based on the grade.
  • Displays an appropriate message for invalid input.
Challenge: Extend the calculator to support addition, subtraction, multiplication, and division. Handle division by zero and invalid operators.

Important Points

  • if executes a block when its condition is truthy.
  • if-else selects between two alternatives.
  • else if checks multiple conditions in order.
  • Nested if statements check conditions inside other conditional blocks.
  • switch selects cases based on an expression's value.
  • break prevents unintended fall-through in switch cases.
  • Use default to handle unmatched switch values when needed.

Summary

JavaScript conditional statements control program flow based on conditions. The if statement handles a single condition, if-else selects between alternatives, else-if checks multiple conditions, and nested if statements allow dependent checks. The switch statement is useful for selecting among multiple exact values. These statements help developers build decision-based programs such as grade calculators, admission checks, and calculators.