JavaScript


Beginners To Experts


The site is under development.

Basic

Chapter 1: JavaScript Basics

In this chapter, we will cover the fundamental concepts of JavaScript, including variables, data types, and operators. These are the building blocks of JavaScript programming.

1.1 Introduction to JavaScript

What is JavaScript?

  • JavaScript is a programming language used to make web pages interactive.
  • It is a client-side language that runs in web browsers but can also be used on servers with Node.js.
  • It allows developers to create dynamic content, handle events, and manipulate the DOM (Document Object Model).

Example 1: Displaying a Message in the Console

console.log("Hello, World!");

Example 2: Displaying a Message on a Webpage

document.write("Welcome to JavaScript!");

Example 3: Showing an Alert Box

alert("This is an alert box!");

1.2 Variables & Data Types

Variables in JavaScript

JavaScript has three ways to declare variables:

  • let (modern, block-scoped)
  • const (constant, cannot be changed)
  • var (old way, avoid using it)

Example 1: Declaring Variables

let name = "John";
const age = 30;
var isStudent = true;

Example 2: Understanding Data Types

let score = 100;
let message = "JavaScript is fun!";
let isActive = false;

Example 3: Checking Data Types with typeof

console.log(typeof 42);
console.log(typeof "Hello");
console.log(typeof true);

1.3 Operators in JavaScript

Operators perform actions on variables and values. The main types are:

  • Arithmetic Operators (for calculations)
  • Comparison Operators (for comparing values)
  • Logical Operators (for decision-making)

1.3.1 Arithmetic Operators

Used for mathematical operations:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulus - remainder)
  • ** (Exponentiation)

Example 1: Performing Arithmetic Operations

let a = 10;
let b = 3;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
console.log(a ** b);

Example 2: Increment and Decrement

let x = 5;
x++;
console.log(x);
let y = 10;
y--;
console.log(y);

Example 3: Using Arithmetic Operators in Expressions

let num1 = 15;
let num2 = 5;
let result = (num1 + num2) * 2;
console.log(result);

1.3.2 Comparison Operators

Used to compare values and return true or false:

  • == (Equal to)
  • === (Strictly equal to - checks type and value)
  • != (Not equal to)
  • !== (Strictly not equal)
  • > (Greater than)
  • < (Less than)
  • >= (Greater than or equal to)
  • <= (Less than or equal to)

Example 1: Basic Comparison

console.log(5 == "5");
console.log(5 === "5");
console.log(10 > 5);
console.log(10 < 5);

Example 2: Comparing Strings

console.log("apple" > "banana");
console.log("100" > "50");
console.log("A" < "B");

Example 3: Checking Inequality

let num = 10;
console.log(num != 5);
console.log(num !== "10");

1.3.3 Logical Operators

Used to combine multiple conditions:

  • && (AND - both conditions must be true)
  • || (OR - at least one condition must be true)
  • ! (NOT - reverses a condition)

Example 1: Using && (AND Operator)

let isLoggedIn = true;
let hasPermission = false;
console.log(isLoggedIn && hasPermission);
console.log(true && true);
console.log(false && true);

Example 2: Using || (OR Operator)

let isWeekend = true;
let isHoliday = false;
console.log(isWeekend || isHoliday);
console.log(false || false);
console.log(true || false);

Example 3: Using ! (NOT Operator)

let isAvailable = false;
console.log(!isAvailable);
console.log(!true);
console.log(!false);

Conclusion of Chapter 1

In this chapter, we covered:

  • Introduction to JavaScript
  • Variables (let, const, var)
  • JavaScript Data Types
  • Operators (Arithmetic, Comparison, Logical)

This knowledge forms the foundation for writing JavaScript programs. In the next chapter, we will learn about Control Flow (If-Else Statements & Loops)!

Chapter 2: Control Flow in JavaScript

Control flow determines how a program executes based on conditions and loops. This chapter covers conditional statements (if-else, switch) and loops (for, while, do-while).

2.1 Conditional Statements

Conditional statements allow the program to execute different code blocks based on conditions.

2.1.1 if Statement

Executes a block of code only if a condition is true.

Example 1: Checking Age

let age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
// Output: "You are an adult." (because 20 is greater than 18)

Example 2: Checking a Number's Sign

let num = -5;
if (num > 0) {
console.log("Positive number.");
}
if (num < 0) {
console.log("Negative number.");
}
// Output: "Negative number." (because -5 is less than 0)

Example 3: Checking if a Variable is Defined

let name = "John";
if (name) {
console.log("The variable has a value.");
}
// Output: "The variable has a value."

2.1.2 if-else Statement

Executes one block if the condition is true, otherwise, executes the else block.

Example 1: Checking Voting Eligibility

let age = 16;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You cannot vote.");
}
// Output: "You cannot vote."

Example 2: Checking Even or Odd Number

let number = 9;
if (number % 2 === 0) {
console.log("Even number.");
} else {
console.log("Odd number.");
}
// Output: "Odd number." (because 9 is not divisible by 2)

Example 3: Checking User Login Status

let isLoggedIn = false;
if (isLoggedIn) {
console.log("Welcome back!");
} else {
console.log("Please log in.");
}
// Output: "Please log in."

2.1.3 if-else if-else Statement

Checks multiple conditions one by one.

Example 1: Grading System

let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
// Output: "Grade: B"

Example 2: Temperature Check

let temperature = 15;
if (temperature >= 30) {
console.log("It's hot.");
} else if (temperature >= 20) {
console.log("It's warm.");
} else {
console.log("It's cold.");
}
// Output: "It's cold."

Example 3: Checking Password Strength

let password = "abc";
if (password.length >= 8) {
console.log("Strong password.");
} else if (password.length >= 5) {
console.log("Moderate password.");
} else {
console.log("Weak password.");
}
// Output: "Weak password."

2.1.4 switch Statement

Used for multiple exact value comparisons.

Example 1: Day of the Week

let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}
// Output: "Wednesday"

Example 2: Checking Traffic Light

let signal = "red";
switch (signal) {
case "red":
console.log("Stop.");
break;
case "yellow":
console.log("Slow down.");
break;
case "green":
console.log("Go.");
break;
default:
console.log("Invalid signal.");
}
// Output: "Stop."

Example 3: Choosing a Beverage

let choice = "coffee";
switch (choice) {
case "tea":
console.log("Serving tea.");
break;
case "coffee":
console.log("Serving coffee.");
break;
case "juice":
console.log("Serving juice.");
break;
default:
console.log("Invalid choice.");
}
// Output: "Serving coffee."

2.2 Loops

Loops repeat a block of code multiple times. The main types are:

  • for loop (fixed repetitions)
  • while loop (runs while a condition is true)
  • do-while loop (runs at least once)

2.2.1 for Loop

Repeats a block a specific number of times.

Example 1: Printing Numbers 1 to 5

for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1, 2, 3, 4, 5

Example 2: Looping Through an Array

let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output: "Apple", "Banana", "Cherry"

Example 3: Printing Even Numbers

for (let i = 2; i <= 10; i += 2) {
console.log(i);
}
// Output: 2, 4, 6, 8, 10

2.2.2 while Loop

Runs while the condition is true.

Example 1: Printing Numbers 1 to 5

let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
// Output: 1, 2, 3, 4, 5

Example 2: Countdown from 5

let count = 5;
while (count > 0) {
console.log(count);
count--;
}
// Output: 5, 4, 3, 2, 1

Example 3: User Login Attempt

let attempts = 3;
while (attempts > 0) {
console.log("Enter your password. Attempts left: " + attempts);
attempts--;
}
// Output: 3 messages prompting for password

2.2.3 do-while Loop

Runs at least once, then checks the condition.

Example 1: Executing a Block Once

let x = 5;
do {
console.log("Runs at least once.");
} while (x < 5);
// Output: "Runs at least once."

Conclusion of Chapter 2

  • Conditional Statements (if-else, switch)
  • Loops (for, while, do-while)

These control flow concepts help make programs dynamic and responsive!

Chapter 3: Functions in JavaScript

Functions are blocks of reusable code that perform a specific task. They help in code organization, reusability, and modularity.

Topics Covered in This Chapter

  • Function Declaration
  • Function Expression
  • Arrow Functions
  • Function Parameters & Return Values
  • Callback Functions

3.1 Function Declaration

A function declaration is the traditional way of defining a function. It can be called before its definition due to JavaScript's hoisting.

Example 1: Function to Greet a User

function greet() {
    console.log("Hello, welcome to JavaScript!");
}
greet();

Output: "Hello, welcome to JavaScript!"


Example 2: Function to Calculate the Square of a Number

function square(num) {
    console.log("The square of", num, "is", num * num);
}
square(4);
square(7);

Output:

"The square of 4 is 16"

"The square of 7 is 49"


Example 3: Function to Add Two Numbers

// Function with two parameters
function add(a, b) {
    console.log("The sum of", a, "and", b, "is", a + b);
}

// Calling the function
add(5, 10);
add(3, 8);

// Output: 
// "The sum of 5 and 10 is 15"
// "The sum of 3 and 8 is 11"
        

Example 4: Function to Check if a Number is Even or Odd

// Function to check even or odd
function checkEvenOdd(num) {
    if (num % 2 === 0) {
        console.log(num, "is even.");
    } else {
        console.log(num, "is odd.");
    }
}

// Calling the function
checkEvenOdd(10);
checkEvenOdd(7);

// Output: 
// "10 is even."
// "7 is odd."
            

Explanation: Uses % (modulo) operator to check if a number is divisible by 2.


Example 5: Function to Convert Celsius to Fahrenheit

// Function to convert Celsius to Fahrenheit
function celsiusToFahrenheit(celsius) {
    let fahrenheit = (celsius * 9/5) + 32;
    console.log(celsius, "Celsius is", fahrenheit, "Fahrenheit.");
}

// Calling the function
celsiusToFahrenheit(0);
celsiusToFahrenheit(25);

// Output:
// "0 Celsius is 32 Fahrenheit."
// "25 Celsius is 77 Fahrenheit."
            

Explanation: Uses the formula F = (C * 9/5) + 32 to convert Celsius to Fahrenheit.

3.2 Function Expression

A function expression assigns a function to a variable. Unlike function declarations, it cannot be called before its definition.

Example 1: Multiplication Function

const multiply = function(a, b) {
    console.log("Product:", a * b);
};
multiply(5, 3);

Output: "Product: 15"

3.3 Arrow Functions (=>)

Arrow functions provide a shorter syntax for writing functions.

1. When to use parentheses () in arrow functions

If the function has a single expression that needs to be returned, you don't need {} and can write it without return:

Example 1: Implicit Return

const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

This is called implicit return.

Example 2: Returning an Object

const getUser = () => ({ name: "John", age: 30 });
console.log(getUser()); // { name: "John", age: 30 }

2. When to use curly braces {}in arrow functions

If the function has multiple lines or you need to write additional logic, you must use {} and explicitly use return:

Example: Using Multiple Statements

const multiply = (a, b) => {
    let result = a * b;
    return result;
};
console.log(multiply(2, 3)); // 6

💡 Note: When using {}, you must explicitly write return if you want to return a value.

Summary:

  • Use () for short, single-expression functions (implicit return).
  • Use {} when the function body has multiple statements or requires return.

Example 1: Function to Double a Number

const double = (num) => {
    console.log(num, "doubled is", num * 2);
};
double(4);
double(7);

Output:

"4 doubled is 8"

"7 doubled is 14"

3.4 Function Parameters & Return Values

Example 1: Function to Calculate Area of a Rectangle

function area(length, width) {
    return length * width;
}
let result = area(5, 10);
console.log("Area:", result);

Output: "Area: 50"

Example 2: Function Returning a Greeting Message


// Function that returns a greeting message
function getGreeting(name) {
    return "Hello, " + name + "!";
}

// Storing and printing the result
let message = getGreeting("Michael");
console.log(message);

// Output: "Hello, Michael!"
    

Explanation:

  • The function returns a greeting instead of logging it directly.

3.5 Callback Functions

Example 1: Function That Accepts a Callback

function processUserInput(name, callback) {
    callback(name);
}
function sayHello(userName) {
    console.log("Hello,", userName);
}
processUserInput("Alice", sayHello);

Output: "Hello, Alice"

Example 2: Using Callback with setTimeout


// Function using setTimeout with callback
setTimeout(() => {
    console.log("This message appears after 3 seconds.");
}, 3000);

// Output (after 3 seconds):
// "This message appears after 3 seconds."
        

Explanation:

  • setTimeout waits 3 seconds before executing the arrow function.

Callback Function Example

A callback function is a function passed as an argument to another function, allowing us to execute code later or under specific conditions.

Example 1: Using a Callback in an Array Method (map)

        // Function that processes an array using a callback
        const numbers = [1, 2, 3, 4, 5];

        // Using map with a callback arrow function
        const squaredNumbers = numbers.map(num => num * num);

        // Printing the result
        console.log("Original numbers:", numbers);
        console.log("Squared numbers:", squaredNumbers);

        // Output:
        // "Original numbers: [1, 2, 3, 4, 5]"
        // "Squared numbers: [1, 4, 9, 16, 25]"

        // Explanation:
        // .map() is an array method that applies a function to each element.
        // The arrow function (num => num * num) takes a number, squares it, and returns the result.
        // The squaredNumbers array stores the modified values.
        

Example 2: Custom Function That Accepts a Callback

const processMessage = (message, callback) => {
    console.log("Processing message:", message);
    callback();
};

const displayComplete = () => {
    console.log("Message processing complete.");
};

processMessage("Hello, this is a callback example!", displayComplete);

// Output:
// "Processing message: Hello, this is a callback example!"
// "Message processing complete."
        

Explanation: The processMessage function accepts a message and a callback function. It prints the message and then executes the callback (displayComplete). The callback function executes only after the message is processed.

Example 3: Using a Callback in a Timer (setTimeout)

const loadData = (callback) => {
    console.log("Loading data...");
    setTimeout(() => {
        console.log("Data loaded successfully!");
        callback();
    }, 2000);
};

const onComplete = () => {
    console.log("Load operation complete.");
};

loadData(onComplete);

// Output:
// "Loading data..."
// (after 2 seconds)
// "Data loaded successfully!"
// "Load operation complete."
        

Explanation: The loadData function simulates loading using setTimeout(). After 2 seconds, it executes the callback function (onComplete). This technique is used in asynchronous operations like API calls.

Example 4: Filtering an Array Using a Callback

const filterNumbers = (numbers, callback) => {
    return numbers.filter(callback);
};

const isEven = num => num % 2 === 0;

const nums = [10, 15, 22, 33, 40];
const evenNumbers = filterNumbers(nums, isEven);

console.log("Original numbers:", nums);
console.log("Even numbers:", evenNumbers);

// Output:
// "Original numbers: [10, 15, 22, 33, 40]"
// "Even numbers: [10, 22, 40]"
        

Explanation: The filterNumbers function accepts an array and a callback function. The callback function (isEven) checks if a number is even. .filter() removes numbers that do not satisfy the condition.

Summary

  • Callbacks allow functions to execute after another function completes.
  • Used in array methods (map, filter), timers (setTimeout), and custom functions.
  • Arrow functions make writing callbacks shorter and cleaner.

Conclusion of Chapter 3

  • Functions help organize and reuse code.
  • Function expressions allow assigning functions to variables.
  • Arrow functions provide a shorter syntax.
  • Functions can return values to be used later.
  • Callback functions allow executing functions asynchronously.

This chapter covered fundamental function concepts that are essential in JavaScript programming!

Conclusion of Chapter 3

  • Functions help organize and reuse code.
  • Function expressions allow assigning functions to variables.
  • Arrow functions provide a shorter syntax.
  • Functions can return values to be used later.
  • Callback functions allow executing functions asynchronously.

Chapter 4: JavaScript Asynchronous Programming (Callbacks, Promises, Async/Await)

JavaScript is single-threaded, meaning it executes one task at a time. To handle long-running tasks (e.g., fetching data from a server), JavaScript provides asynchronous programming techniques to prevent blocking execution.

Topics Covered in This Chapter

  • Callbacks – Functions passed into other functions to run later.
  • Promises – Handle async tasks more cleanly than callbacks.
  • Async/Await – A modern and readable way to work with asynchronous code.
  • Real-World Examples – File reading, API fetching, and database querying.

4.1 Callbacks (Handling Asynchronous Code Manually)

A callback function is executed after another function finishes.

Example 1: Simulating a File Read Operation

const readFile = (fileName, callback) => {
    console.log(`Reading file: ${fileName}...`);
    setTimeout(() => {
        console.log("File read complete.");
        callback("File data: Lorem ipsum..."); // Pass file data to callback
    }, 2000);
};

const displayFile = (fileData) => {
    console.log("Displaying file content:", fileData);
};

readFile("document.txt", displayFile);

// Output:
// Reading file: document.txt...
// (after 2 seconds)
// File read complete.
// Displaying file content: File data: Lorem ipsum...
        

Explanation: The readFile function simulates reading a file and delays the response using setTimeout(). The callback is called only after the file is read, ensuring we get the correct data.

4.2 Promises (Handling Async Code More Elegantly)

A Promise is an object representing a value that may be available now, later, or never.

resolve: Task completed successfully.

reject: Task failed.

Example 2: Simulating an API Call with Promises

const fetchUserData = (userId) => {
    return new Promise((resolve, reject) => {
        console.log(`Fetching user data for ID: ${userId}...`);

        setTimeout(() => {
            if (userId === 1) {
                resolve({ id: 1, name: "Michael", email: "michael@example.com" });
            } else {
                reject("User not found.");
            }
        }, 3000);
    });
};

fetchUserData(1)
    .then(user => console.log("User data:", user)) // Runs if resolved
    .catch(error => console.log("Error:", error)); // Runs if rejected

// Output (after 3 seconds):
// Fetching user data for ID: 1...
// User data: { id: 1, name: "Michael", email: "michael@example.com" }
        

Explanation: fetchUserData() returns a Promise that resolves with user data if the userId is 1. If userId !== 1, the Promise rejects, returning an error message. .then() executes if the Promise resolves successfully, and .catch() handles errors (e.g., user not found).

4.3 Async/Await (Cleaner and More Readable than Promises)

The async/await syntax makes handling Promises more readable.

Example 3: Fetching Product Data with Async/Await

const getProduct = async (productId) => {
    console.log(`Fetching product details for ID: ${productId}...`);

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (productId === 100) {
                resolve({ id: 100, name: "Laptop", price: 1200 });
            } else {
                reject("Product not found.");
            }
        }, 2000);
    });
};

const displayProduct = async () => {
    try {
        const product = await getProduct(100); // Waits for the Promise to resolve
        console.log("Product details:", product);
    } catch (error) {
        console.log("Error:", error); // Catches rejection
    }
};

displayProduct();

// Output:
// Fetching product details for ID: 100...
// (after 2 seconds)
// Product details: { id: 100, name: "Laptop", price: 1200 }
        

Explanation: getProduct() simulates fetching product details using a Promise. await getProduct(100) waits until the Promise resolves or rejects. try...catch handles both successful and failed requests.

4.4 Real-World Example: Fetching API Data

Let's simulate fetching data from an API using the Fetch API with async/await.

const fetchPosts = async () => {
    try {
        console.log("Fetching posts...");
        
        const response = await fetch("https://jsonplaceholder.typicode.com/posts"); // Fetch data
        const posts = await response.json(); // Convert response to JSON
        
        console.log("Posts fetched successfully:", posts.slice(0, 2)); // Display first 2 posts
    } catch (error) {
        console.log("Error fetching posts:", error);
    }
};

fetchPosts();

// Output (Example):
// Fetching posts...
// Posts fetched successfully: [{ id: 1, title: "Post 1", body: "Lorem ipsum..." }, { id: 2, title: "Post 2", body: "Lorem ipsum..." }]
        

Explanation: fetch() sends a network request to fetch posts. await response.json() parses the response into a JavaScript object. If successful, the first two posts are displayed.

Conclusion of Chapter 4

  • Callbacks – Functions executed after another function completes.
  • Promises – A more structured way to handle asynchronous tasks (resolve, reject).
  • Async/Await – Simplifies Promises for better readability.
  • Real-world usage – Fetching files, API calls, and database operations.

Mastering asynchronous programming is crucial for handling real-world JavaScript applications!

Chapter 5: JavaScript Events & Event Handling

Events are actions that happen in the browser, such as user interactions or system-generated actions. JavaScript allows us to handle events and execute code in response to them.

Topics Covered in This Chapter

  • What is an Event?
  • Adding Event Listeners
  • Event Types
  • Event Object
  • Event Bubbling and Capturing
  • Preventing Default Behavior

5.1 What is an Event?

An event is a user interaction or system-triggered action that JavaScript can respond to. Examples of events include:

  • User Actions: click, mouseover, keypress, etc.
  • System Actions: load, resize, scroll, etc.

5.2 Adding Event Listeners

Event listeners are functions that wait for an event to occur and execute a callback when the event happens.

// Function to display a message when the button is clicked
 const handleClick = () => {
    console.log("Button clicked!");
 };

// Adding event listener for a click event
document.getElementById("myButton").addEventListener("click", handleClick);

 Explanation:
 • getElementById("myButton"): This selects the button by its ID.
 • .addEventListener("click", handleClick): Adds an event listener to the button for the click event.
 • When the button is clicked, the handleClick function is executed, which prints "Button clicked!".
        

5.3 Event Types

JavaScript supports many types of events that correspond to user interactions and browser behaviors. Common event types include:

  • Mouse Events: click, mouseover, mouseout, mousemove
  • Keyboard Events: keydown, keyup, keypress
  • Form Events: submit, change, input

Example 2: Handling Keyboard Input

// Function to handle key press event
// const handleKeyPress = (event) => {
//     console.log("Key pressed:", event.key);  // Displays the key that was pressed
// };

// Adding event listener for the 'keydown' event
// document.addEventListener("keydown", handleKeyPress);

// Explanation:
// • event.key: Accesses the specific key pressed on the keyboard.
// • The handleKeyPress function is executed whenever a key is pressed, printing the key to the console.
        

5.4 Event Object

When an event is triggered, the browser passes an event object to the event handler. This object contains useful information about the event, such as the target element and the type of event.

5.4 Example 3: Using Event Object in a Click Event

// Function to handle click event and display event details
// const handleClick = (event) => {
//     console.log("Event Type:", event.type);  // Displays the event type (e.g., "click")
//     console.log("Clicked Element:", event.target);  // Displays the element that was clicked
// };

// Adding event listener for click event
// document.getElementById("myButton").addEventListener("click", handleClick);

// Explanation:
// • event.type: Displays the type of the event (e.g., click).
// • event.target: Refers to the HTML element that triggered the event (the button in this case).
        

5.5 Example 4: Demonstrating Event Bubbling

// Parent element click handler
// const handleParentClick = () => {
//     console.log("Parent clicked!");
// };

// Child element click handler
// const handleChildClick = (event) => {
//     console.log("Child clicked!");
//     // Stopping event propagation (bubbling)
//     event.stopPropagation();
// };

// Adding event listeners
// document.getElementById("parent").addEventListener("click", handleParentClick);
// document.getElementById("child").addEventListener("click", handleChildClick);

// Explanation:
// • Event Bubbling: If you click the child element, both the child and parent elements will trigger their click handlers.
// • event.stopPropagation() stops the event from bubbling to the parent element. The child click handler will be executed, but the parent will not be triggered.
        

5.6 Preventing Default Behavior

Some events have default behaviors, such as form submissions or anchor tag navigation. You can prevent this default behavior using event.preventDefault().

Example 5: Preventing Form Submission

// Function to handle form submission and prevent default behavior
 const handleSubmit = (event) => {
     event.preventDefault();  // Prevent the form from submitting
     console.log("Form submission prevented!");
 };

 Adding event listener for form submit event
 document.getElementById("myForm").addEventListener("submit", handleSubmit);

 Explanation:
 • event.preventDefault() stops the form from submitting when the user clicks the submit button.
 • This is useful for validating form data before submission.
        

Conclusion of Chapter 5: JavaScript Events & Event Handling

  • Events are user interactions or browser actions that JavaScript can handle.
  • Event Listeners allow you to trigger specific actions when events occur.
  • The Event Object contains information about the event and its target.
  • Event Bubbling and Capturing determine how events propagate in the DOM.
  • Prevent Default Behavior is used to stop actions like form submissions or navigation.

Chapter 6: JavaScript Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a paradigm that organizes code into objects, which contain properties (data) and methods (functions) to manipulate that data. JavaScript supports OOP using prototypes and classes.

Topics Covered in This Chapter

  • Objects and Object Literals
  • Constructor Functions
  • Prototypes and Prototype Inheritance
  • ES6 Classes
  • Encapsulation, Inheritance, and Polymorphism

6.1 Objects and Object Literals

Objects store key-value pairs and allow us to group related data and functions.

Example 1: Creating an Object Literal

        
        // Defining an object using object literal syntax
        const person = {
            name: "Michael",      // Property: name
            age: 30,              // Property: age
            greet: function() {   // Method: greet()
                return `Hello, my name is ${this.name}.`;
            }
        };

        // Accessing properties and calling a method
        console.log(person.name);  // Output: Michael
        console.log(person.age);   // Output: 30
        console.log(person.greet()); // Output: Hello, my name is Michael.
       
        

Explanation:

  • person is an object with properties (name, age) and a method (greet).
  • The this keyword refers to the current object.
  • We access properties using dot notation (person.name).
  • We call a method using parentheses (person.greet()).

Example 2: Adding and Removing Properties

         
        // Adding a new property dynamically
        person.job = "Software Developer";

        // Removing a property
        delete person.age;

        console.log(person); 
        // Output: { name: 'Michael', greet: [Function: greet], job: 'Software Developer' }
        
        

Explanation:

  • We can add properties dynamically using person.job.
  • We can remove properties using delete.

6.2 Constructor Functions

A constructor function is a blueprint for creating multiple objects.

Example 3: Creating Objects with a Constructor

        
        // Constructor function for a Car object
        function Car(brand, model, year) {
            this.brand = brand;   // Assigning parameters to object properties
            this.model = model;
            this.year = year;
            this.getDetails = function() {
                return `${this.brand} ${this.model} (${this.year})`;
            };
        }

        // Creating instances of Car
        const car1 = new Car("Toyota", "Corolla", 2022);
        const car2 = new Car("Honda", "Civic", 2023);

        console.log(car1.getDetails()); // Output: Toyota Corolla (2022)
        console.log(car2.getDetails()); // Output: Honda Civic (2023)
       
        

Explanation:

  • Car is a constructor function that initializes a new object with brand, model, and year.
  • new Car(...) creates new instances.
  • getDetails() returns a formatted string.

6.3 Prototypes and Prototype Inheritance

In JavaScript, objects inherit properties and methods from their prototype.

Example 4: Adding Methods Using Prototypes

       
        // Constructor function
        function Person(name, age) {
            this.name = name;
            this.age = age;
        }

        // Adding a method using prototype
        Person.prototype.sayHello = function() {
            return `Hi, I'm ${this.name} and I'm ${this.age} years old.`;
        };

        const person1 = new Person("Alice", 25);
        const person2 = new Person("Bob", 28);

        console.log(person1.sayHello()); // Output: Hi, I'm Alice and I'm 25 years old.
        console.log(person2.sayHello()); // Output: Hi, I'm Bob and I'm 28 years old.
        
        

Explanation:

  • Methods added to Person.prototype are shared across all instances.
  • sayHello() is available to all Person objects.

6.4 ES6 Classes (Modern Syntax for OOP)

ES6 introduced the class keyword for a cleaner syntax.

Example 5: Creating Classes in JavaScript

     
        // Defining a class
        class Animal {
            constructor(name, species) {
                this.name = name;
                this.species = species;
            }
            
            makeSound() {
                return `${this.name} makes a sound.`;
            }
        }

        // Creating instances
        const dog = new Animal("Buddy", "Dog");
        const cat = new Animal("Whiskers", "Cat");

        console.log(dog.makeSound()); // Output: Buddy makes a sound.
        console.log(cat.makeSound()); // Output: Whiskers makes a sound.
       
        

Explanation:

  • class Animal defines a blueprint with a constructor.
  • Methods are declared inside the class (makeSound()).
  • Instances are created using new.