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 Functions

Learn how to create reusable functions, pass parameters, return values, use function expressions and write arrow functions with practical examples.

Function Declaration Parameters Arguments Return Statement Arrow Functions

1. What Is a Function in JavaScript?

A function is a reusable block of code designed to perform a particular task. We write the code inside a function and execute it whenever required by calling that function.

Suppose we want to display a welcome message ten times. Instead of writing the same console.log() statement ten times, we can create a function and call it whenever we need the message.

Definition: A function is a reusable block of code that performs a specific task and can optionally accept inputs and return an output.

Why Do We Need Functions?

  • Code Reusability: Write code once and use it multiple times.
  • Less Duplication: Avoid writing the same statements repeatedly.
  • Easy Maintenance: Update the logic in one place.
  • Better Organization: Divide a large program into smaller tasks.
  • Easy Testing: Test individual functions separately.

2. Function Working Diagram

A function generally follows three steps: define the function, call it, and execute the statements inside it.

Step 1

Function Definition

function greet() { ... }

Define the task that the function will perform.

↓
Step 2

Function Call

greet();

Call the function to execute its code.

↓
Step 3

Function Execution

console.log("Welcome!");

The statements inside the function execute.

Important: Defining a normal function does not execute its body. You must call it to run its statements.

3. Function Declaration and Syntax

A function declaration uses the function keyword followed by the function name, parentheses and a block of code.

JavaScript - Syntax
function functionName() {
    // Statements to execute
}

functionName();

Understanding the Syntax

Syntax Meaning
function Keyword used to declare a function.
functionName The name used to identify and call the function.
() Parentheses contain the function parameters, if any.
{ } The function body contains the statements to execute.
functionName() Calls the function.

4. Simple Function Example

Let's create a function that displays a welcome message.

JavaScript - Example 1
function greet() {
    console.log("Welcome to CIIT Training Institute!");
}

greet();
greet();

Expected Output

Welcome to CIIT Training Institute!
Welcome to CIIT Training Institute!

Explanation

  1. The greet() function is declared.
  2. The message is written inside the function body.
  3. The first call executes the function and displays the message.
  4. The second call executes the same function again.

We have written the message only once, but we can execute it multiple times. This is the main advantage of a function.

5. Function Parameters and Arguments

Functions can accept values so that the same function can work with different inputs.

  • Parameter: A variable specified in the function definition.
  • Argument: A value supplied when the function is called.
JavaScript - Example 2
function greetStudent(name) {
    console.log("Hello, " + name + "!");
}

greetStudent("Samadhan");
greetStudent("Pradnya");

Expected Output

Hello, Samadhan!
Hello, Pradnya!

Parameter and Argument Diagram

Function Call

greetStudent("Samadhan")

↓
Parameter Receives the Value

name = "Samadhan"

↓
Function Output

Hello, Samadhan!

Here, name is the parameter. The strings "Samadhan" and "Pradnya" are arguments.

6. Function with Multiple Parameters

A function can accept multiple parameters separated by commas. For example, an addition function can accept two numbers.

JavaScript - Example 3
function add(a, b) {
    console.log(a + b);
}

add(10, 20);
add(50, 30);

Expected Output

30
80

How Values Are Assigned

Function Call Parameter a Parameter b Result
add(10, 20) 10 20 30
add(50, 30) 50 30 80

7. Return Statement in JavaScript

The return statement sends a value back to the code that called the function. This value can be stored in a variable, printed, or used in another calculation.

JavaScript - Example 4
function add(a, b) {
    return a + b;
}

let result = add(10, 20);

console.log(result);

Expected Output

30

Understanding the Return Value

  1. add(10, 20) calls the function.
  2. The function calculates 10 + 20.
  3. return a + b sends back the value 30.
  4. The returned value is stored in result.
  5. console.log(result) displays the value.
Remember: A function without an explicit return value returns undefined. The return statement also ends the current function execution.

Difference Between console.log() and return

console.log() return
Displays a value in the console. Sends a value back to the caller.
Does not automatically return that displayed value. The returned value can be stored and reused.
Useful for displaying information and debugging. Useful for calculations and further processing.

8. Default Parameters

A default parameter provides a fallback value when an argument is omitted or its value is undefined.

JavaScript - Example 5
function greet(name = "Student") {
    console.log("Hello, " + name);
}

greet("Samadhan");
greet();

Expected Output

Hello, Samadhan
Hello, Student

When greet("Samadhan") is called, the supplied value is used. When greet() is called without an argument, the default value "Student" is used.

9. Function Expression

A function expression creates a function and assigns it to a variable. The function can be called through that variable.

JavaScript - Example 6
const subtract = function(a, b) {
    return a - b;
};

let result = subtract(20, 8);

console.log(result);

Expected Output

12

Here, the function is assigned to the variable subtract. We use subtract(20, 8) to execute it.

Note: This example uses a function expression assigned to a const variable. The variable cannot be reassigned, but the function can still be called.

10. Arrow Functions

An arrow function is a concise way to write a function expression. It uses the => operator.

JavaScript - Example 7
const add = (a, b) => {
    return a + b;
};

console.log(add(10, 15));

Expected Output

25

Short Arrow Function

When an arrow function contains a single expression and does not use braces, the expression's result is returned automatically.

JavaScript - Example 8
const square = number => number * number;

console.log(square(5));

Expected Output

25

Function Types Comparison

Type Example Syntax Usage
Function Declaration function add(a, b) { ... } Named reusable functions.
Function Expression const add = function(a, b) { ... }; Assign a function to a variable.
Arrow Function const add = (a, b) => a + b; Concise function expressions.

11. Practical Example: Calculate Student Marks

In this example, one function calculates total marks and another calculates the average. The returned value from the first function is passed to the second.

JavaScript - Practical Example
function calculateTotal(mark1, mark2, mark3) {
    return mark1 + mark2 + mark3;
}

function calculateAverage(total) {
    return total / 3;
}

let total = calculateTotal(80, 75, 90);
let average = calculateAverage(total);

console.log("Total Marks: " + total);
console.log("Average Marks: " + average.toFixed(2));

Expected Output

Total Marks: 245
Average Marks: 81.67

Step-by-Step Execution

  1. calculateTotal(80, 75, 90) calculates the total.
  2. The total value 245 is returned.
  3. The returned value is passed to calculateAverage(total).
  4. The average is calculated by dividing 245 by 3.
  5. toFixed(2) formats the average to two decimal places.

12. Function Return Flow Diagram

This diagram shows how input values move through a function and how the returned result is used by the calling code.

Input
Pass Arguments

calculateTotal(80, 75, 90)

↓
Processing
Execute Function Logic

80 + 75 + 90 = 245

↓
Return
Send Result to Caller

return 245;

↓
Output
Use the Returned Value

Total Marks: 245

13. Common Mistakes in Functions

Common Mistake Correct Understanding
Defining a function but never calling it. Call the function to execute its body.
Expecting console.log() to return a result. Use return when the caller needs a value.
Passing arguments in the wrong order. Pass arguments in the intended parameter order.
Forgetting parentheses when calling a function. Use functionName() to call a regular function.
Writing code after an unconditional return statement. Place required statements before the return statement.
Using braces in an arrow function but forgetting return. Use an explicit return inside a block body.

14. Practice Tasks

Task 1: Calculate Rectangle Area

Create a function named calculateArea that accepts length and width and returns the rectangle's area.

Requirements:
  • Accept two parameters: length and width.
  • Calculate area using length * width.
  • Return the calculated value.
  • Call the function with length 10 and width 5.
  • Display the result using console.log().
Expected Output:
Area: 50

Task 2: Check Even or Odd

Create a function named checkEvenOdd that accepts a number and returns whether the number is even or odd.

Requirements:
  • Accept one parameter.
  • Use the modulus operator %.
  • Return an appropriate message.
  • Test the function with 10 and 7.
Expected Output:
10 is Even
7 is Odd

Task 3: Convert Celsius to Fahrenheit

Create a function that accepts a temperature in Celsius and returns the Fahrenheit temperature.

Formula:

Fahrenheit = (Celsius * 9 / 5) + 32

Expected Output for 25°C:
Fahrenheit: 77

Summary

JavaScript functions help us organize code into reusable blocks that can perform specific tasks.

  • A function is defined and then called to execute its code.
  • Parameters receive the input values supplied as arguments.
  • Functions can accept multiple parameters.
  • The return statement sends a value back to the caller.
  • Default parameters provide fallback values.
  • Function expressions assign functions to variables.
  • Arrow functions provide a concise way to write function expressions.
  • Functions improve code reuse, readability and maintainability.