Lecture 1 / 52
Topic 01 - Introduction to JavaScript

JS Introduction

Syllabus Topic Beginner
What is JavaScript?

JavaScript is one of the core technologies of the web. It is used to make websites interactive and dynamic. While HTML creates the structure and CSS handles styling, JavaScript adds behavior and functionality.

Overview

JavaScript was originally created to run inside web browsers, but today it is used everywhere — frontend development, backend servers, mobile apps, games, APIs, and even desktop applications.

With JavaScript, developers can create features such as:

  • Interactive buttons and menus
  • Form validation
  • Animations and sliders
  • Real-time updates without refreshing pages
  • Web applications and games

JavaScript is lightweight, easy to learn, and supported by all modern browsers.

Example

script.js
// JavaScript Example

alert("Welcome to JavaScript!");

console.log("JavaScript is running");

The alert() function displays a popup message, while console.log() prints output inside the browser console.

Why Learn JavaScript?

Feature Description
Frontend Development Creates interactive user interfaces
Backend Development Can run servers using Node.js
Cross Platform Works on browsers, mobile, and desktop
Large Community Millions of developers and libraries available

Practice

Practice Task

Create a JavaScript file that shows an alert saying "Hello World" and prints your name in the browser console.

Topic 02 - Introduction to JavaScript

Where To

Syllabus Topic Beginner
Where to Write JavaScript

JavaScript code can be written directly inside HTML pages or inside separate external files.

Overview

JavaScript is usually placed inside the <script> tag. This tag can appear inside the <head> or <body> section of an HTML document.

Most developers place scripts before the closing </body> tag because it allows the HTML content to load first.

Internal JavaScript

index.html
<!-- Internal JavaScript -->

<script>
    alert("Hello from JavaScript");
</script>

This method is useful for small projects or quick testing.

External JavaScript

index.html
<!-- External JavaScript File -->

<script src="script.js"></script>

External files improve organization and allow the same script to be reused across multiple pages.

Benefits of External Files

  • Cleaner HTML code
  • Better code organization
  • Reusable scripts
  • Faster page loading through browser caching

Practice

Practice Task

Create an HTML file and connect an external JavaScript file named script.js. Print a message in the console.

Topic 03 - Introduction to JavaScript

Output

Syllabus Topic Beginner
JavaScript Output Methods

JavaScript provides different ways to display output inside browsers and web pages.

Overview

Output methods are used to show information to users or developers. Different methods are used depending on the situation.

Using innerHTML

script.js
// Change HTML content

document.getElementById("demo").innerHTML = "Hello JavaScript";

This method changes the content of an HTML element.

Using document.write()

script.js
// Write directly to page

document.write("Learning JavaScript");

document.write() is mainly used for testing and simple examples.

Using alert()

script.js
// Popup message

alert("Welcome!");

The alert() function displays a popup dialog box in the browser.

Using console.log()

script.js
// Output in browser console

console.log("Debug message");

Developers commonly use console.log() for debugging and testing code.

Comparison of Output Methods

Method Purpose
innerHTML Change webpage content
alert() Show popup messages
console.log() Debugging output
document.write() Direct page output

Practice

Practice Task

Create a webpage that uses all four JavaScript output methods to display different messages.

Topic 04 - Introduction to JavaScript

Statements

Syllabus Topic JavaScript Basics
What are Statements?

A JavaScript statement is a command that tells the browser what action to perform. Programs are made up of multiple statements executed one after another.

Overview

Every JavaScript program is built using statements. A statement can declare variables, display output, perform calculations, make decisions, or repeat actions using loops.

JavaScript executes statements line by line from top to bottom unless control structures like conditions or loops change the flow.

Basic Statements

statements.js
let name = "Ahmed";
let age = 20;

console.log(name);
console.log(age);

document.write("Welcome to JavaScript");

Each line above is a separate statement. Statements usually end with a semicolon ;.

Expression Statements

Expressions become statements when JavaScript executes them to produce an action or value.

expressions.js
let x = 10 + 5;
x++;

console.log(x);

The expression 10 + 5 calculates a value, while x++ increases the value of x by 1.

Conditional Statements

Conditional statements allow JavaScript to make decisions based on conditions.

if_statement.js
let marks = 85;

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

The code inside the if block runs only if the condition is true.

Loop Statements

Loops repeat statements multiple times automatically.

loop.js
for (let i = 1; i <= 5; i++) {
    console.log("Count:", i);
}

The loop runs the statement five times while increasing the value of i.

Block Statements

Curly braces { } group multiple statements together into a block.

block.js
if (true) {
    console.log("Statement 1");
    console.log("Statement 2");
    console.log("Statement 3");
}

Empty Statements

JavaScript also allows empty statements using only a semicolon. These are rarely used but can appear in loops.

empty.js
let i = 0;

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

Practice

Practice Task

Create a JavaScript program that:

  • Declares two variables
  • Prints their sum
  • Checks whether the result is even or odd
  • Uses a loop to print numbers from 1 to 5
Topic 05 - Introduction to JavaScript

Syntax

Syllabus Topic JavaScript Basics
What is Syntax?

Syntax refers to the set of rules that define how JavaScript code must be written. Incorrect syntax causes syntax errors and prevents programs from running.

Overview

JavaScript syntax includes rules for variables, keywords, operators, statements, spacing, brackets, semicolons, and naming conventions.

Variables & Keywords

variables.js
let username = "Alex";
const pi = 3.14;
var age = 18;

console.log(username);
console.log(pi);
console.log(age);

JavaScript keywords such as let, const, and if have special meanings and cannot be used as variable names.

Case Sensitivity

JavaScript is case-sensitive. Variable names with different capitalization are treated as different variables.

case.js
let city = "London";
let City = "Paris";

console.log(city);
console.log(City);

Code Blocks

Curly braces define blocks of code for functions, loops, and conditions.

blocks.js
if (true) {
    console.log("Inside block");
}

Whitespace & Indentation

Spaces and line breaks improve readability. Proper indentation makes code easier to understand and debug.

indentation.js
function greet() {
    console.log("Hello");
    console.log("Welcome");
}

Semicolons

Semicolons terminate statements. JavaScript can insert them automatically, but writing them explicitly is considered good practice.

semicolon.js
let x = 10;
let y = 20;

console.log(x + y);

Practice

Practice Task

Write a JavaScript program that:

  • Declares variables using let and const
  • Uses proper indentation
  • Prints values using console.log()
  • Creates an if statement with braces
Topic 06 - Introduction to JavaScript

Comments

Syllabus Topic JavaScript Basics
Why Comments Matter

Comments are notes written inside code to explain logic, improve readability, and help developers understand programs more easily.

Overview

JavaScript ignores comments during execution. They are only for humans reading the code.

Single-Line Comments

Single-line comments begin with //.

single_comment.js
// Store user age
let age = 20;

// Print age to console
console.log(age);

Multi-Line Comments

Multi-line comments start with /* and end with */.

multiline.js
/*
This program calculates
the total price of items
*/

let total = 100;
console.log(total);

Commenting Out Code

Developers often comment out code temporarily during testing or debugging.

debug.js
let score = 90;

// console.log("Debugging score:", score);

console.log(score);

Writing Good Comments

Good comments explain why code exists, not just what it does.

good_comments.js
// Apply 10% discount for premium members
total = total - (total * 0.10);

Practice

Practice Task

Create a JavaScript program that:

  • Uses single-line comments
  • Uses a multi-line comment
  • Comments out one line of code
  • Explains the purpose of variables using comments
Topic 07 - Introduction to JavaScript

Variables

Syllabus Topic Beginner
Understanding Variables

Variables are containers used to store data in JavaScript. They allow programs to save and reuse values during execution.

Overview

Variables are one of the most important concepts in programming. Instead of writing the same value repeatedly, developers store it inside a variable and use the variable name whenever needed.

JavaScript provides three ways to declare variables:

  • var — older method
  • let — modern and recommended
  • const — used for constant values

Declaring Variables

script.js
// Variable declarations

let name = "Ahmed";

const country = "India";

var age = 20;

console.log(name);
console.log(country);
console.log(age);

The console.log() function displays variable values in the browser console.

Rules for Naming Variables

Rule Example
Must start with a letter, _ or $ userName
Cannot start with numbers 1name ❌
Case sensitive age and Age are different
No spaces allowed user_name

Updating Variables

script.js
// Updating values

let score = 10;

score = 20;

console.log(score);

Variables declared with let can be updated later.

Constants

script.js
// Constant value

const pi = 3.14;

console.log(pi);

Variables declared with const cannot be reassigned after creation.

Practice

Practice Task

Create variables for your name, age, and favorite programming language. Print all values using console.log().

Topic 08 - Introduction to JavaScript

Operators

Syllabus Topic Beginner
What are Operators?

Operators are symbols used to perform operations on values and variables.

Overview

JavaScript operators are used for calculations, comparisons, assignments, and logical operations.

Operators make programs dynamic and allow decision making inside applications.

Arithmetic Operators

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)

Assignment Operators

script.js
// Assignment operators

let x = 10;

x += 5;

console.log(x);

The += operator adds a value and stores the result back into the variable.

Comparison Operators

script.js
// Comparison operators

let a = 5;

console.log(a == 5);

console.log(a > 2);

console.log(a < 10);

Comparison operators return either true or false.

Logical Operators

Operator Description
&& Logical AND
|| Logical OR
! Logical NOT

Practice

Practice Task

Create variables and use arithmetic, comparison, and logical operators to test different conditions.

Topic 09 - Introduction to JavaScript

Arithmetic

Syllabus Topic Beginner
JavaScript Arithmetic

JavaScript can perform mathematical calculations using arithmetic operators.

Overview

Arithmetic operations are commonly used in applications such as calculators, games, billing systems, and data processing.

JavaScript supports addition, subtraction, multiplication, division, and more.

Basic Arithmetic Operations

script.js
// Arithmetic operations

let a = 10;
let b = 5;

console.log(a + b);

console.log(a - b);

console.log(a * b);

console.log(a / b);

Modulus Operator

script.js
// Modulus operator

let num = 10;

console.log(num % 3);

The modulus operator returns the remainder after division.

Increment and Decrement

script.js
// Increment and decrement

let x = 5;

x++;

console.log(x);

x--;

console.log(x);

The ++ operator increases a value by 1, while -- decreases it by 1.

Operator Precedence

JavaScript follows mathematical order of operations.

script.js
// Operator precedence

let result = 5 + 2 * 3;

console.log(result);

Multiplication happens before addition, so the result will be 11.

Practice

Practice Task

Create a simple calculator that performs addition, subtraction, multiplication, and division using JavaScript variables.

Topic 10 - Introduction to JavaScript

Assignment

Syllabus Topic Core Concepts
What is Assignment?

Assignment means storing a value inside a variable using the assignment operator =. JavaScript also provides shorthand assignment operators like +=, -=, *=, and more to update values quickly.

Overview

Assignment operators are one of the most commonly used parts of JavaScript. They allow programs to save data, update counters, calculate totals, and modify variables dynamically while the program runs.

Whenever you write:

assign.js
let score = 10;

The value 10 is assigned to the variable score.

Basic Assignment Operators

Operator Description Example
= Assign value x = 5
+= Add and assign x += 2
-= Subtract and assign x -= 3
*= Multiply and assign x *= 4
/= Divide and assign x /= 2
%= Modulus and assign x %= 2

Example

script.js
// Basic assignment
let marks = 50;

console.log(marks);

// Add and assign
marks += 10;
console.log(marks);

// Subtract and assign
marks -= 5;
console.log(marks);

// Multiply and assign
marks *= 2;
console.log(marks);

// Divide and assign
marks /= 5;
console.log(marks);

Assignment with Strings

Assignment operators can also work with strings. The += operator joins text together.

strings.js
let message = "Hello";

message += " World";

console.log(message);

Increment & Decrement

JavaScript provides special operators for increasing or decreasing values by 1.

increment.js
let count = 1;

count++;
console.log(count);

count--;
console.log(count);

Real World Example

Assignment operators are heavily used in counters, shopping carts, scoreboards, banking systems, and loops.

cart.js
let total = 0;

total += 200;
total += 150;
total += 50;

console.log("Final Total:", total);

Practice

Practice Task

Create a variable called salary with value 1000. Add a bonus of 500, subtract tax of 200, then print the final salary.

Topic 11 - Introduction to JavaScript

Data Types

Syllabus Topic Core Concepts
What are Data Types?

Data types define the kind of data a variable can store. JavaScript supports numbers, strings, booleans, arrays, objects, and more.

Overview

Every value in JavaScript belongs to a specific data type. Understanding data types is important because JavaScript behaves differently depending on the type of value being used.

Primitive Data Types

Data Type Example
String "Hello"
Number 25
Boolean true
Undefined undefined
Null null

Example

script.js
let name = "Ahmed";
let age = 21;
let isStudent = true;
let city;
let car = null;

console.log(typeof name);
console.log(typeof age);
console.log(typeof isStudent);
console.log(typeof city);
console.log(typeof car);

Arrays

Arrays store multiple values inside a single variable.

array.js
let fruits = ["Apple", "Mango", "Banana"];

console.log(fruits[0]);
console.log(fruits.length);

Objects

Objects store data in key-value pairs.

object.js
let student = {
    name: "Ali",
    age: 20,
    course: "JavaScript"
};

console.log(student.name);
console.log(student.course);

Type Conversion

JavaScript can convert one data type into another.

convert.js
let num = "100";

console.log(Number(num) + 50);

let value = 25;

console.log(String(value));

Practice

Practice Task

Create variables for your name, age, and whether you are a student. Print their values and data types using typeof.

Topic 12 - Introduction to JavaScript

Functions

Syllabus Topic Core Concepts
What are Functions?

Functions are reusable blocks of code that perform a specific task. Instead of writing the same code repeatedly, you can place it inside a function and call it whenever needed.

Overview

Functions make programs organized, reusable, and easier to maintain. A function can accept input values called parameters and can also return a result.

Function Syntax

function.js
function greet() {
    console.log("Welcome to JavaScript");
}

greet();

Functions with Parameters

Parameters allow functions to receive data.

params.js
function greet(name) {
    console.log("Hello " + name);
}

greet("Ahmed");
greet("Sara");

Return Statement

The return keyword sends a value back from the function.

return.js
function add(a, b) {
    return a + b;
}

let result = add(5, 3);

console.log(result);

Arrow Functions

Arrow functions provide a shorter syntax for writing functions.

arrow.js
const square = (num) => {
    return num * num;
};

console.log(square(4));

Default Parameters

Default parameters are used when no argument is passed.

default.js
function welcome(user = "Guest") {
    console.log("Welcome " + user);
}

welcome();
welcome("Ali");

Practice

Practice Task

Create a function that accepts two numbers and prints their multiplication table result.

Topic 13 - Introduction to JavaScript

Objects

Syllabus Topic Intermediate
Understanding Objects

Objects are used to store related data and functionality together. They are one of the most powerful features in JavaScript.

Overview

An object contains properties and values. Properties describe the object, while values store the actual data.

Objects help organize information in a structured way. For example, instead of storing a user's name, age, and country in separate variables, all values can be stored inside one object.

Creating an Object

script.js
// Creating an object

const user = {
    name: "Ahmed",
    age: 20,
    country: "India"
};

console.log(user);

The object above contains three properties: name, age, and country.

Accessing Object Properties

script.js
// Accessing properties

const car = {
    brand: "Toyota",
    model: "Corolla"
};

console.log(car.brand);

console.log(car["model"]);

Properties can be accessed using dot notation or bracket notation.

Adding New Properties

script.js
// Adding properties

const student = {
    name: "Ali"
};

student.grade = "A";

console.log(student);

JavaScript objects are dynamic, meaning new properties can be added anytime.

Object Methods

script.js
// Object methods

const person = {
    name: "Sara",

    greet: function() {
        console.log("Hello!");
    }
};

person.greet();

Functions stored inside objects are called methods.

Object Properties Table

Concept Description
Property Stores data inside an object
Method A function inside an object
Dot Notation Access values using a dot
Bracket Notation Access values using square brackets

Practice

Practice Task

Create an object called book with properties for title, author, and price. Print all values in the console.

Topic 14 - Introduction to JavaScript

Events

Syllabus Topic Intermediate
What are Events?

Events are actions that happen in the browser, such as clicks, typing, loading pages, or moving the mouse.

Overview

JavaScript can respond to user interactions using events. Events make websites interactive and dynamic.

For example, clicking a button can display a message, submit a form, or change webpage content.

Click Event

index.html
<!-- Click event example -->

<button onclick="showMessage()">
    Click Me
</button>

<script>
function showMessage() {
    alert("Button clicked!");
}
</script>

The function runs automatically when the button is clicked.

Mouse Events

Event Description
onclick Triggered when clicked
onmouseover Triggered when mouse enters element
onmouseout Triggered when mouse leaves element
ondblclick Triggered on double click

Keyboard Events

index.html
<!-- Keyboard event example -->

<input type="text" onkeyup="typing()">

<script>
function typing() {
    console.log("User is typing");
}
</script>

The onkeyup event runs whenever a key is released.

Event Listener

script.js
// Using addEventListener

const btn = document.getElementById("btn");

btn.addEventListener("click", function() {
    console.log("Button clicked");
});

addEventListener() is the modern and recommended way to handle events.

Practice

Practice Task

Create a button that changes the background color of the webpage when clicked.

Topic 15 - Introduction to JavaScript

Strings

Syllabus Topic Beginner
Working with Strings

Strings are used to store and manipulate text in JavaScript.

Overview

A string is a sequence of characters surrounded by quotes. JavaScript supports single quotes, double quotes, and backticks.

Strings are commonly used for names, messages, user input, and webpage content.

Creating Strings

script.js
// Creating strings

let firstName = "Ahmed";

let city = 'Delhi';

let message = `Welcome`;

console.log(firstName);
console.log(city);
console.log(message);

String Concatenation

script.js
// Combining strings

let first = "Hello";

let second = "World";

let result = first + " " + second;

console.log(result);

The + operator combines strings together.

Template Literals

script.js
// Template literals

let name = "Sara";

console.log(`Hello ${name}`);

Template literals allow variables to be inserted directly into strings using ${ }.

Useful String Methods

Method Description
length Returns string length
toUpperCase() Converts to uppercase
toLowerCase() Converts to lowercase
includes() Checks if text exists

String Methods Example

script.js
// String methods

let text = "JavaScript";

console.log(text.length);

console.log(text.toUpperCase());

console.log(text.includes("Script"));

Practice

Practice Task

Create a program that asks for a user's name and displays a welcome message using template literals.

Topic 16 - Introduction to JavaScript

String Methods

Syllabus Topic Core Concepts
Understanding String Methods

Strings are used to store text in JavaScript. String methods are built-in functions that help us manipulate, search, format, and process text easily.

Overview

JavaScript provides many useful string methods for working with text. You can convert text to uppercase, find characters, extract parts of a string, replace text, and much more.

Strings are immutable in JavaScript, which means methods do not change the original string. Instead, they return a new modified string.

Creating Strings

strings.js
let name = "JavaScript";

console.log(name);

Common String Methods

Method Description
length Returns total characters
toUpperCase() Converts to uppercase
toLowerCase() Converts to lowercase
includes() Checks if text exists
indexOf() Returns position of text
slice() Extracts part of string
replace() Replaces text
trim() Removes extra spaces

Example

script.js
let text = " Hello JavaScript ";

console.log(text.length);

console.log(text.toUpperCase());

console.log(text.toLowerCase());

console.log(text.includes("Java"));

console.log(text.indexOf("Java"));

console.log(text.slice(7, 17));

console.log(text.replace("JavaScript", "World"));

console.log(text.trim());

Splitting Strings

The split() method converts a string into an array.

split.js
let sentence = "HTML CSS JavaScript";

let words = sentence.split(" ");

console.log(words);

Template Literals

Template literals use backticks and allow variables inside strings using ${}.

template.js
let user = "Ahmed";
let age = 20;

console.log(`My name is ${user} and I am ${age} years old.`);

Escape Characters

Escape characters are used for special formatting inside strings.

escape.js
console.log("Hello\nWorld");

console.log("JavaScript\tTutorial");

console.log("She said \"Hello\"");

Practice

Practice Task

Create a string containing your full name. Print its length, convert it to uppercase, replace your first name with another name, and split the string into words.

Topic 17 - Introduction to JavaScript

Numbers

Syllabus Topic Core Concepts
Understanding Numbers

Numbers are used to store numeric values in JavaScript. They can be integers, decimals, positive values, or negative values.

Overview

JavaScript uses a single number type for integers and floating-point numbers. Numbers are commonly used in calculations, counters, marksheets, shopping carts, banking systems, and scientific calculations.

Creating Numbers

numbers.js
let a = 10;
let b = 5.5;
let c = -20;

console.log(a);
console.log(b);
console.log(c);

Arithmetic Operations

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)

Example

script.js
let x = 20;
let y = 6;

console.log(x + y);

console.log(x - y);

console.log(x * y);

console.log(x / y);

console.log(x % y);

Special Numeric Values

JavaScript also provides special numeric values.

special.js
console.log(Infinity);

console.log(-Infinity);

console.log(NaN);

Converting Strings to Numbers

convert.js
let value = "100";

console.log(Number(value));

console.log(parseInt("25px"));

console.log(parseFloat("10.5"));

Math Object

The Math object provides useful mathematical operations.

math.js
console.log(Math.round(4.7));

console.log(Math.floor(4.9));

console.log(Math.ceil(4.1));

console.log(Math.sqrt(81));

console.log(Math.pow(2, 4));

console.log(Math.random());

Practice

Practice Task

Create two number variables and perform all arithmetic operations on them. Also print the square root of one number using the Math object.

Topic 18 - Introduction to JavaScript

Number Methods

Syllabus Topic Core Concepts
Understanding Number Methods

Number methods help format, convert, and manipulate numeric values in JavaScript.

Overview

JavaScript provides built-in number methods for converting numbers into strings, controlling decimal places, formatting values, and checking numeric validity.

Common Number Methods

Method Description
toString() Converts number to string
toFixed() Sets decimal places
toPrecision() Formats total digits
Number() Converts value to number
isNaN() Checks if value is not a number

Example

script.js
let num = 15.6789;

console.log(num.toString());

console.log(num.toFixed(2));

console.log(num.toPrecision(4));

console.log(Number("100"));

console.log(isNaN("Hello"));

Formatting Decimal Numbers

The toFixed() method is commonly used for currency and financial calculations.

decimal.js
let price = 199.4567;

console.log(price.toFixed(2));

Checking Numeric Values

You can check whether a value is numeric using isNaN().

check.js
console.log(isNaN(100));

console.log(isNaN("JavaScript"));

Parsing Numbers

JavaScript can extract numbers from strings.

parse.js
console.log(parseInt("50px"));

console.log(parseFloat("99.99 dollars"));

Practice

Practice Task

Create a decimal number variable. Print it with 1, 2, and 3 decimal places using toFixed(). Then convert the number into a string.

Topic 19 - Introduction to JavaScript

Arrays

Syllabus Topic Template
What is an Array?

An Array in JavaScript is used to store multiple values in a single variable. Instead of creating many separate variables, we can store all related data inside one array.

Arrays are very useful when working with lists such as student names, marks, products, cities, numbers, and many other collections of data.

Overview

Arrays are one of the most important data structures in JavaScript. They allow us to store values in an ordered way. Every value inside an array has a position called an index.

Array indexing starts from 0. This means:

  • First element → index 0
  • Second element → index 1
  • Third element → index 2
script.js
let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
Output

Apple
Banana
Mango

Creating Arrays

Arrays are created using square brackets [].

script.js
let numbers = [10, 20, 30, 40];

console.log(numbers);

Different Types of Data in Arrays

JavaScript arrays can store different types of values together.

script.js
let data = ["John", 25, true, 99.5];

console.log(data);

Changing Array Values

We can change any value in an array using its index number.

script.js
let colors = ["Red", "Blue", "Green"];

colors[1] = "Yellow";

console.log(colors);
Important Note

If you try to access an index that does not exist, JavaScript returns undefined.

Array Length

The length property is used to find the total number of elements in an array.

script.js
let subjects = ["Math", "Science", "English"];

console.log(subjects.length);
Output

3

Example

script.js
let students = ["Ali", "Sara", "Ahmed"];

console.log("First Student:", students[0]);
console.log("Second Student:", students[1]);
console.log("Third Student:", students[2]);

console.log("Total Students:", students.length);

Practice

Practice Task

Create an array named cars with 4 car names.

Perform the following operations:

  • Print the first car name
  • Print the last car name
  • Change the second car name
  • Print the total number of cars
Topic 20 - Introduction to JavaScript

Array Methods

Syllabus Topic Template
Introduction to Array Methods

Array methods are built-in functions provided by JavaScript to perform operations on arrays.

These methods help us add, remove, search, combine, and modify array elements easily.

Overview

JavaScript provides many useful array methods. Some methods modify the original array while others return a new value.

Commonly used array methods include:

  • push()
  • pop()
  • shift()
  • unshift()
  • includes()
  • indexOf()

push()

The push() method adds a new element at the end of the array.

script.js
let fruits = ["Apple", "Banana"];

fruits.push("Mango");

console.log(fruits);

pop()

The pop() method removes the last element from an array.

script.js
let fruits = ["Apple", "Banana", "Mango"];

fruits.pop();

console.log(fruits);

shift()

The shift() method removes the first element from an array.

script.js
let colors = ["Red", "Blue", "Green"];

colors.shift();

console.log(colors);

unshift()

The unshift() method adds a new element at the beginning of the array.

script.js
let colors = ["Blue", "Green"];

colors.unshift("Red");

console.log(colors);

includes()

The includes() method checks whether a value exists inside an array.

script.js
let subjects = ["Math", "Science", "English"];

console.log(subjects.includes("Math"));
Output

true

indexOf()

The indexOf() method returns the index position of a value.

script.js
let animals = ["Cat", "Dog", "Lion"];

console.log(animals.indexOf("Dog"));
Output

1

Example

script.js
let numbers = [10, 20, 30];

numbers.push(40);
numbers.pop();

console.log(numbers);

numbers.unshift(5);

console.log(numbers);

Practice

Practice Task

Create an array named games.

Perform the following tasks:

  • Add a new game using push()
  • Remove the last game using pop()
  • Add a game at the beginning using unshift()
  • Check whether a game exists using includes()
Topic 21 - Introduction to JavaScript

Array Sort

Syllabus Topic Template
Introduction to Array Sorting

Sorting means arranging data in a particular order such as ascending or descending.

JavaScript provides the sort() method to sort array elements.

Overview

The sort() method sorts array elements alphabetically by default.

Sorting is very useful in real-world applications such as:

  • Sorting student marks
  • Sorting product prices
  • Sorting names alphabetically
  • Sorting leaderboard scores

Sorting Strings

When sorting strings, JavaScript arranges them alphabetically.

script.js
let fruits = ["Mango", "Apple", "Banana"];

fruits.sort();

console.log(fruits);
Output

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

Sorting Numbers

Sorting numbers can sometimes give unexpected results because JavaScript converts numbers into strings.

script.js
let numbers = [100, 20, 5, 40];

numbers.sort();

console.log(numbers);
Important Note

The output may not be correct for numbers because JavaScript sorts them as strings by default.

Correct Number Sorting

To sort numbers properly, we use a compare function.

script.js
let numbers = [100, 20, 5, 40];

numbers.sort(function(a, b){
    return a - b;
});

console.log(numbers);
Output

[5, 20, 40, 100]

Descending Order

To sort numbers in descending order, reverse the subtraction.

script.js
let marks = [45, 90, 20, 70];

marks.sort(function(a, b){
    return b - a;
});

console.log(marks);

Example

script.js
let cities = ["Delhi", "Mumbai", "Chandigarh"];

cities.sort();

console.log(cities);

let scores = [50, 10, 80, 30];

scores.sort(function(a, b){
    return a - b;
});

console.log(scores);

Practice

Practice Task

Create an array of numbers and perform the following:

  • Sort the array in ascending order
  • Sort the array in descending order
  • Create an array of names and sort them alphabetically
Topic 22 - Introduction to JavaScript

Array Iteration

Syllabus Topic Template
Introduction to Array Iteration

Array Iteration means accessing array elements one by one. In JavaScript, iteration is used to perform operations on every element of an array.

Iteration is very important because it helps developers process large amounts of data easily.

Overview

JavaScript provides different ways to iterate through arrays. We can use loops or special array methods to access elements.

Common methods used for array iteration are:

  • for loop
  • for...of loop
  • forEach()
  • map()
  • filter()

Using for Loop

The for loop is the most common way to iterate through an array.

script.js
let fruits = ["Apple", "Banana", "Mango"];

for(let i = 0; i < fruits.length; i++){
    console.log(fruits[i]);
}
Output

Apple
Banana
Mango

Using for...of Loop

The for...of loop is a simpler way to iterate through array values.

script.js
let colors = ["Red", "Blue", "Green"];

for(let color of colors){
    console.log(color);
}

forEach() Method

The forEach() method executes a function for every array element.

script.js
let numbers = [10, 20, 30];

numbers.forEach(function(value){
    console.log(value);
});
Important Note

The forEach() method does not return a new array. It is mainly used for displaying or processing values.

map() Method

The map() method creates a new array after performing operations on each element.

script.js
let numbers = [1, 2, 3];

let result = numbers.map(function(value){
    return value * 2;
});

console.log(result);
Output

[2, 4, 6]

filter() Method

The filter() method creates a new array containing only matching elements.

script.js
let ages = [12, 18, 25, 10, 30];

let adults = ages.filter(function(age){
    return age >= 18;
});

console.log(adults);
Output

[18, 25, 30]

Difference Between map() and filter()

  • map() modifies every element
  • filter() selects specific elements
  • Both methods return a new array

Example

script.js
let marks = [50, 70, 90];

marks.forEach(function(mark){
    console.log("Mark:", mark);
});

let updatedMarks = marks.map(function(mark){
    return mark + 5;
});

console.log(updatedMarks);

Practice

Practice Task

Create an array named prices with 5 values.

Perform the following tasks:

  • Print all values using for loop
  • Print all values using forEach()
  • Create a new array with all prices doubled using map()
  • Create a filtered array containing prices greater than 100
Topic 23 - Introduction to JavaScript

Dates

Syllabus Topic Template
Introduction to Dates

JavaScript provides the Date object to work with dates and time.

Dates are commonly used in clocks, calendars, websites, booking systems, and many real-world applications.

Overview

The Date object helps developers get current date and time information.

We can:

  • Get current date
  • Get current time
  • Extract year, month, and day
  • Create custom dates

Creating a Date Object

A new date object is created using the new Date() constructor.

script.js
let today = new Date();

console.log(today);

Getting Current Year

The getFullYear() method returns the current year.

script.js
let date = new Date();

console.log(date.getFullYear());

Getting Current Month

The getMonth() method returns the month number.

Important Note

Months start from 0 in JavaScript. January is 0 and December is 11.

script.js
let date = new Date();

console.log(date.getMonth());

Getting Current Date

The getDate() method returns the current day of the month.

script.js
let date = new Date();

console.log(date.getDate());

Getting Current Time

We can also get hours, minutes, and seconds.

script.js
let time = new Date();

console.log(time.getHours());
console.log(time.getMinutes());
console.log(time.getSeconds());

Creating Custom Dates

We can create our own custom dates by passing values inside Date().

script.js
let birthday = new Date(2005, 5, 15);

console.log(birthday);

Example

script.js
let now = new Date();

console.log("Year:", now.getFullYear());
console.log("Month:", now.getMonth());
console.log("Date:", now.getDate());
console.log("Hours:", now.getHours());

Practice

Practice Task

Create a program that:

  • Displays current year
  • Displays current month
  • Displays current date
  • Displays current hours and minutes
Topic 24 - Introduction to JavaScript

Date Formats

Syllabus Topic Template
Introduction to Date Formats

JavaScript provides different ways to display and format dates.

Formatting dates helps make date information easier for users to understand.

Overview

Date formatting is commonly used in:

  • Web applications
  • Attendance systems
  • Booking websites
  • Digital clocks

JavaScript provides built-in methods to convert dates into readable formats.

toDateString()

The toDateString() method displays only the date portion.

script.js
let today = new Date();

console.log(today.toDateString());

toTimeString()

The toTimeString() method displays only the time portion.

script.js
let today = new Date();

console.log(today.toTimeString());

toLocaleDateString()

The toLocaleDateString() method formats the date according to local settings.

script.js
let today = new Date();

console.log(today.toLocaleDateString());

toLocaleTimeString()

The toLocaleTimeString() method formats time according to local settings.

script.js
let today = new Date();

console.log(today.toLocaleTimeString());

Full Date and Time

The toLocaleString() method displays both date and time together.

script.js
let today = new Date();

console.log(today.toLocaleString());
Example Output

5/27/2026, 10:30:45 AM

Example

script.js
let date = new Date();

console.log(date.toDateString());
console.log(date.toTimeString());
console.log(date.toLocaleDateString());
console.log(date.toLocaleTimeString());
console.log(date.toLocaleString());

Practice

Practice Task

Create a program that displays:

  • Current date only
  • Current time only
  • Full local date and time
  • Date using toDateString()
Topic 25 - Introduction to JavaScript

Date Get Methods

Syllabus Topic Template
Introduction to Date Get Methods

JavaScript provides different get methods to extract information from a Date object.

These methods help developers retrieve year, month, date, hours, minutes, seconds, and many other values from the current date and time.

Overview

Date get methods are used to read date and time values from a Date object.

Commonly used Date get methods include:

  • getFullYear()
  • getMonth()
  • getDate()
  • getDay()
  • getHours()
  • getMinutes()
  • getSeconds()

getFullYear()

The getFullYear() method returns the current year.

script.js
let date = new Date();

console.log(date.getFullYear());
Example Output

2026

getMonth()

The getMonth() method returns the month number.

Important Note

Months start from 0 in JavaScript. January is 0 and December is 11.

script.js
let date = new Date();

console.log(date.getMonth());

getDate()

The getDate() method returns the day of the month.

script.js
let date = new Date();

console.log(date.getDate());

getDay()

The getDay() method returns the day number of the week.

  • 0 → Sunday
  • 1 → Monday
  • 2 → Tuesday
  • 3 → Wednesday
  • 4 → Thursday
  • 5 → Friday
  • 6 → Saturday
script.js
let date = new Date();

console.log(date.getDay());

getHours()

The getHours() method returns the current hour.

script.js
let time = new Date();

console.log(time.getHours());

getMinutes()

The getMinutes() method returns current minutes.

script.js
let time = new Date();

console.log(time.getMinutes());

getSeconds()

The getSeconds() method returns current seconds.

script.js
let time = new Date();

console.log(time.getSeconds());

Example

script.js
let now = new Date();

console.log("Year:", now.getFullYear());
console.log("Month:", now.getMonth());
console.log("Date:", now.getDate());
console.log("Day:", now.getDay());
console.log("Hours:", now.getHours());
console.log("Minutes:", now.getMinutes());
console.log("Seconds:", now.getSeconds());

Practice

Practice Task

Create a JavaScript program that:

  • Displays current year
  • Displays current month
  • Displays current day
  • Displays current hours and minutes
  • Displays current seconds
Topic 26 - Introduction to JavaScript

Date Set Methods

Syllabus Topic Template
Introduction to Date Set Methods

Date set methods are used to modify date and time values inside a Date object.

These methods help developers change year, month, date, hours, minutes, and seconds according to program requirements.

Overview

JavaScript provides many set methods to update date and time values.

Common Date set methods are:

  • setFullYear()
  • setMonth()
  • setDate()
  • setHours()
  • setMinutes()
  • setSeconds()

setFullYear()

The setFullYear() method changes the year of a date object.

script.js
let date = new Date();

date.setFullYear(2030);

console.log(date);

setMonth()

The setMonth() method changes the month value.

Important Note

Months start from 0. January is 0 and December is 11.

script.js
let date = new Date();

date.setMonth(11);

console.log(date);

setDate()

The setDate() method changes the day of the month.

script.js
let date = new Date();

date.setDate(15);

console.log(date);

setHours()

The setHours() method changes the hour value.

script.js
let time = new Date();

time.setHours(10);

console.log(time);

setMinutes()

The setMinutes() method changes minutes.

script.js
let time = new Date();

time.setMinutes(30);

console.log(time);

setSeconds()

The setSeconds() method changes seconds.

script.js
let time = new Date();

time.setSeconds(45);

console.log(time);

Example

script.js
let customDate = new Date();

customDate.setFullYear(2028);
customDate.setMonth(5);
customDate.setDate(20);
customDate.setHours(9);
customDate.setMinutes(15);

console.log(customDate);

Practice

Practice Task

Create a Date object and:

  • Change the year
  • Change the month
  • Change the date
  • Change the hours
  • Change the minutes
Topic 27 - Introduction to JavaScript

Math

Syllabus Topic Template
Introduction to Math Object

JavaScript provides a built-in Math object that helps perform mathematical calculations.

The Math object contains useful properties and methods for working with numbers.

Overview

The Math object is commonly used for:

  • Rounding numbers
  • Finding maximum and minimum values
  • Generating random numbers
  • Calculating powers and square roots

Math.round()

The Math.round() method rounds a number to the nearest integer.

script.js
console.log(Math.round(4.6));
console.log(Math.round(4.3));
Output

5
4

Math.ceil()

The Math.ceil() method rounds a number upward.

script.js
console.log(Math.ceil(4.1));

Math.floor()

The Math.floor() method rounds a number downward.

script.js
console.log(Math.floor(4.9));

Math.max()

The Math.max() method returns the largest value.

script.js
console.log(Math.max(10, 20, 50, 5));

Math.min()

The Math.min() method returns the smallest value.

script.js
console.log(Math.min(10, 20, 50, 5));

Math.random()

The Math.random() method generates a random number between 0 and 1.

script.js
console.log(Math.random());

Math.pow()

The Math.pow() method calculates power values.

script.js
console.log(Math.pow(2, 3));
Output

8

Math.sqrt()

The Math.sqrt() method returns the square root of a number.

script.js
console.log(Math.sqrt(64));
Output

8

Example

script.js
console.log(Math.round(5.7));
console.log(Math.floor(9.9));
console.log(Math.ceil(2.1));

console.log(Math.max(5, 10, 15));
console.log(Math.min(5, 10, 15));

console.log(Math.pow(3, 2));
console.log(Math.sqrt(81));

Practice

Practice Task

Create a JavaScript program that:

  • Rounds a decimal number
  • Finds the maximum value
  • Finds the minimum value
  • Finds square root of a number
  • Generates a random number
Topic 28 - Introduction to JavaScript

Random

JavaScript Basics Numbers
About Random Numbers

JavaScript provides the Math.random() method to generate random numbers. Random numbers are commonly used in games, OTP generators, dice rolling, password generators, and random selections.

Overview

The Math.random() method returns a random decimal number between 0 and 1.

Important Note

The number generated will always be less than 1.

Basic Random Number

script.js
let num = Math.random();

console.log(num);

Output Example

0.54738291

Random Number Between 1 and 10

We can multiply the random number and use Math.floor() to get whole numbers.

script.js
let number = Math.floor(Math.random() * 10) + 1;

console.log(number);

Output Example

7

Dice Roll Example

script.js
let dice = Math.floor(Math.random() * 6) + 1;

console.log("Dice Number:", dice);

Applications of Random Numbers

  • Games
  • Password generators
  • Lottery systems
  • Random colors
  • Quiz applications

Practice

Practice Task

Create a program that generates a random number between 1 and 100.

Bonus: Create a simple dice rolling simulator.

Topic 29 - Introduction to JavaScript

Booleans

JavaScript Basics Data Types
About Booleans

A Boolean is a data type that can have only two values: true or false.

Overview

Booleans are mainly used in conditions, comparisons, loops, and decision-making statements.

Boolean Values

script.js
let isStudent = true;
let isLoggedIn = false;

console.log(isStudent);
console.log(isLoggedIn);

Output

true
false

Boolean from Comparison

script.js
console.log(10 > 5);
console.log(3 == 7);

Output

true
false

Boolean in If Statement

script.js
let raining = true;

if (raining) {
    console.log("Take an umbrella");
}

Falsy Values in JavaScript

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

Practice

Practice Task

Create a Boolean variable named isAdmin and print its value.

Also check whether 20 is greater than 15.

Topic 30 - Introduction to JavaScript

Comparisons

JavaScript Basics Operators
About Comparisons

Comparison operators are used to compare two values. The result is always true or false.

Overview

JavaScript provides several comparison operators to compare numbers, strings, and variables.

Comparison Operators

Operator Meaning
== Equal to
=== Strict equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example

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

Output

true
false
true
false

Difference Between == and ===

Important Difference

== compares only values while === compares both value and data type.

Using Comparisons in Conditions

script.js
let age = 18;

if (age >= 18) {
    console.log("Eligible to vote");
}

Practice

Practice Task

Write a program that checks whether a number is greater than 50.

Also compare two strings using == and ===.

Topic 31 - Introduction to JavaScript

Conditions

Syllabus Topic Decision Making
What are Conditions?

Conditions in JavaScript are used to make decisions in a program. They allow code to run only when a certain condition is true. JavaScript mainly uses if, else if, and else statements for conditional logic.

Overview

Conditional statements help programs behave differently based on user input or values. For example:

  • If marks are above 40 → display "Pass"
  • If age is 18 or above → allow voting
  • If password is correct → login successful

Syntax of if Statement

script.js
if(condition){
    // code to execute
}

Example 1 — Simple if

script.js
let age = 20;

if(age >= 18){
    console.log("You can vote");
}

Output

You can vote

Example 2 — if...else

script.js
let number = 5;

if(number % 2 === 0){
    console.log("Even Number");
}else{
    console.log("Odd Number");
}

Output

Odd Number

Example 3 — else if

script.js
let marks = 75;

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

Output

Grade B

Important Comparison Operators

Operator Meaning
== Equal to
=== Strict equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to

Practice

Practice Task

Write a JavaScript program that checks whether a number is positive, negative, or zero using if...else if...else.

Topic 32 - Introduction to JavaScript

Switch

Syllabus Topic Control Statement
What is Switch?

The switch statement is used to execute one block of code from many options. It is often used instead of multiple if...else statements.

Overview

The switch statement compares a value with different cases. When a matching case is found, that block of code executes.

Syntax

script.js
switch(expression){

    case value1:
        // code
        break;

    case value2:
        // code
        break;

    default:
        // default code
}

Example

script.js
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

Why break is Important?

The break statement stops execution after a matching case. Without break, the next cases also execute.

Practice

Practice Task

Create a switch program that displays month names based on numbers from 1 to 12.

Topic 33 - Introduction to JavaScript

Loop For

Syllabus Topic Loops
What is a for Loop?

A for loop is used to repeat a block of code multiple times. It is very useful when the number of repetitions is known.

Overview

Instead of writing the same code many times, loops automate repetition. A for loop has three parts:

  • Initialization
  • Condition
  • Increment / Decrement

Syntax

script.js
for(initialization; condition; increment){

    // code block
}

Example 1 — Print Numbers

script.js
for(let i = 1; i <= 5; i++){

    console.log(i);
}

Output

1
2
3
4
5

Example 2 — Even Numbers

script.js
for(let i = 2; i <= 10; i += 2){

    console.log(i);
}

Output

2
4
6
8
10

Loop Flow

  1. Initialization runs once
  2. Condition is checked
  3. Code executes if condition is true
  4. Increment/decrement happens
  5. Condition is checked again

Practice

Practice Task

Write a for loop that prints the multiplication table of 5.

Topic 34 - Introduction to JavaScript

Loop While

Syllabus Topic Loops
What is a while Loop?

A while loop repeatedly executes a block of code as long as the condition remains true. It is useful when the number of repetitions is unknown.

Overview

In a while loop, the condition is checked first. If the condition is true, the code executes. The process continues until the condition becomes false.

Syntax

script.js
while(condition){

    // code block
}

Example 1 — Print Numbers

script.js
let i = 1;

while(i <= 5){

    console.log(i);

    i++;
}

Output

1
2
3
4
5

Example 2 — Even Numbers

script.js
let num = 2;

while(num <= 10){

    console.log(num);

    num += 2;
}

Output

2
4
6
8
10

Important Note

Always update the variable inside the loop. Otherwise, the loop may run forever and create an infinite loop.

Practice

Practice Task

Write a while loop that prints numbers from 10 to 1 in reverse order.

Topic 35 - Introduction to JavaScript

Break

Syllabus Topic Loop Control
What is break?

The break statement is used to stop a loop or switch statement immediately. When break executes, the program exits the loop.

Overview

The break keyword is commonly used when a specific condition is met and there is no need to continue the loop further.

Syntax

script.js
break;

Example — break in for Loop

script.js
for(let i = 1; i <= 10; i++){

    if(i === 5){
        break;
    }

    console.log(i);
}

Output

1
2
3
4

How it Works

  1. Loop starts from 1
  2. Numbers print normally
  3. When i becomes 5, break runs
  4. The loop stops immediately

break in switch

In switch statements, break prevents execution of the next cases.

Practice

Practice Task

Write a loop that prints numbers from 1 to 20 and stops when the number becomes 12.

Topic 36 - Introduction to JavaScript

Type Conversion

Syllabus Topic JavaScript Basics
What is Type Conversion?

Type conversion means changing one data type into another. For example, converting a string into a number or a number into a string.

Overview

JavaScript supports two types of conversions:

  • Implicit Conversion — done automatically by JavaScript
  • Explicit Conversion — done manually by the programmer

Convert String to Number

script.js
let num = "100";

console.log(Number(num));

Output

100

Convert Number to String

script.js
let number = 50;

console.log(String(number));

Output

50

Implicit Conversion Example

script.js
let result = "5" + 2;

console.log(result);

Output

52

Common Conversion Methods

Method Description
Number() Converts value to number
String() Converts value to string
Boolean() Converts value to boolean
parseInt() Converts string to integer

Practice

Practice Task

Convert the string "250" into a number and add 50 to it.

Topic 37 - Introduction to JavaScript

Bitwise

Syllabus Topic Operators
What are Bitwise Operators?

Bitwise operators work directly on the binary form (0 and 1) of numbers. These operators are mainly used in low-level programming, permissions, graphics programming, and performance optimization.

Overview

JavaScript converts numbers into 32-bit binary values before performing bitwise operations.

Operator Name Example
& AND 5 & 1
| OR 5 | 1
^ XOR 5 ^ 1
~ NOT ~5
<< Left Shift 5 << 1
>> Right Shift 5 >> 1

Example

script.js
// Bitwise AND
let a = 5;
let b = 1;

console.log(a & b);

// Bitwise OR
console.log(a | b);

// Left Shift
console.log(a << 1);

Output

1
5
10

Explanation

The number 5 in binary is 101 and 1 is 001.

  • AND (&) returns 1 only if both bits are 1.
  • OR (|) returns 1 if at least one bit is 1.
  • Left Shift (<<) shifts bits to the left.

Practice

Practice Task

Create two variables and perform all bitwise operators on them. Display the results using console.log().

Topic 38 - Introduction to JavaScript

RegExp

Syllabus Topic Advanced
What is RegExp?

RegExp stands for Regular Expression. It is used to search, match, and validate text patterns in JavaScript.

Overview

Regular expressions are useful for validating emails, phone numbers, passwords, and searching text.

Common Methods

  • test() → checks if pattern exists
  • match() → returns matched values
  • replace() → replaces text
  • search() → returns match position

Example

script.js
// Regular Expression Example

let text = "Welcome to JavaScript";

let pattern = /JavaScript/;

console.log(pattern.test(text));

console.log(text.search(pattern));

console.log(text.replace("JavaScript", "JS"));

Output

true
11
Welcome to JS

Explanation

  • /JavaScript/ is a regular expression pattern.
  • test() checks whether the text contains the pattern.
  • search() returns the starting position.
  • replace() replaces matching text.

Practice

Practice Task

Create a regular expression to check whether a string contains the word "HTML".

Topic 39 - Introduction to JavaScript

Errors

Syllabus Topic Debugging
What are Errors?

Errors occur when JavaScript code contains mistakes or invalid operations. JavaScript provides error handling using try, catch, and finally.

Overview

Error handling prevents programs from crashing and helps developers manage unexpected situations.

Types of Errors

  • Syntax Error
  • Reference Error
  • Type Error
  • Range Error

Example

script.js
// Error Handling Example

try {
    let result = num + 10;
    console.log(result);
}

catch(error) {
    console.log("An error occurred");
}

finally {
    console.log("Program finished");
}

Output

An error occurred
Program finished

Explanation

  • try contains risky code.
  • catch runs if an error occurs.
  • finally always executes.

Practice

Practice Task

Create a program using try and catch to handle an undefined variable error.

Topic 40 - Introduction to JavaScript

Scope

Syllabus Topic Core Concept
What is Scope?

Scope determines where variables can be accessed in a program. JavaScript has global scope, function scope, and block scope.

Overview

Variables declared with var are function scoped, while let and const are block scoped.

Types of Scope

  • Global Scope → Accessible everywhere.
  • Function Scope → Accessible only inside a function.
  • Block Scope → Accessible only inside a block { }.

Example

script.js
// Global Scope
let name = "John";

function showName() {

    // Function Scope
    let age = 20;

    console.log(name);
    console.log(age);
}

showName();

// Block Scope
{
    let city = "Delhi";
    console.log(city);
}

Output

John
20
Delhi

Explanation

  • name is global and can be used anywhere.
  • age works only inside the function.
  • city works only inside the block.

Practice

Practice Task

Create variables using var, let, and const inside different scopes and test where they can be accessed.

Topic 41 - Introduction to JavaScript

Hoisting

Syllabus Topic Important
What is Hoisting?

Hoisting is JavaScript's default behavior of moving declarations to the top before code execution.

Overview

Variables declared with var are hoisted and initialized with undefined. Variables declared with let and const are also hoisted but cannot be used before declaration.

Example

script.js
// Hoisting Example

console.log(x);

var x = 10;

console.log(x);

Output

undefined
10

Explanation

JavaScript moves the declaration of x to the top. The variable exists before assignment, so the first output becomes undefined.

Example with let

console.log(y);

let y = 5;

This code gives an error because let variables cannot be accessed before declaration.

Practice

Practice Task

Create examples using var, let, and const to observe hoisting behavior.

Topic 42 - Introduction to JavaScript

Strict Mode

Syllabus Topic Best Practice
What is Strict Mode?

Strict mode is a feature in JavaScript that helps write safer and cleaner code by preventing common mistakes.

Overview

Strict mode is enabled by writing "use strict" at the beginning of a script or function.

Advantages

  • Prevents accidental global variables.
  • Shows errors for unsafe actions.
  • Makes debugging easier.
  • Improves code quality.

Example

script.js
// Strict Mode Example

"use strict";

x = 10;

console.log(x);

Output

ReferenceError: x is not defined

Explanation

In normal JavaScript, assigning a value to an undeclared variable creates a global variable. Strict mode prevents this and throws an error.

Correct Version

"use strict";

let x = 10;

console.log(x);

Practice

Practice Task

Enable strict mode and create examples that show errors for undeclared variables and duplicate parameters.

Topic 43 - Introduction to JavaScript

JSON

Syllabus Topic Data Handling
What is JSON?

JSON stands for JavaScript Object Notation. It is a lightweight format used to store and exchange data between applications and servers.

JSON data is written using key-value pairs and is easy for humans and machines to read.

JSON Syntax Rules

  • Data is stored in key-value pairs.
  • Keys must be inside double quotes.
  • Values can be strings, numbers, arrays, booleans, objects, or null.
  • Objects are written inside curly braces { }.

Example JSON Object

data.json
{
    "name": "Rahul",
    "age": 20,
    "course": "BCA",
    "isStudent": true
}

JSON.parse()

JSON.parse() converts JSON string into a JavaScript object.

script.js
let text = '{"name":"Aman","age":21}';

let obj = JSON.parse(text);

console.log(obj.name);
console.log(obj.age);

Output

Aman
21

JSON.stringify()

JSON.stringify() converts a JavaScript object into a JSON string.

script.js
let student = {
    name: "Riya",
    marks: 90
};

let jsonData = JSON.stringify(student);

console.log(jsonData);

Output

{"name":"Riya","marks":90}

Why JSON is Used

  • Sending data between server and browser
  • Storing configuration data
  • Working with APIs
  • Saving application data

Practice

Practice Task

Create a JavaScript object with your name, city, and age. Convert it into JSON using JSON.stringify().

Then convert the JSON string back into an object using JSON.parse().

Topic 44 - Introduction to JavaScript

Forms

Syllabus Topic User Input
JavaScript Forms

Forms are used to collect user input such as name, email, password, and messages. JavaScript can validate and process form data before sending it to the server.

Common Form Elements

  • Text Box
  • Password Field
  • Radio Button
  • Checkbox
  • Submit Button
  • Textarea

Simple Form Example

index.html
<form>
    Name:
    <input type="text" id="username">

    <br><br>

    <button onclick="showName()" type="button">
        Submit
    </button>
</form>
script.js
function showName() {
    let name = document.getElementById("username").value;

    alert("Welcome " + name);
}

Output

When the user enters a name and clicks the button, an alert message appears.

Form Validation Example

script.js
function validate() {

    let name = document.getElementById("username").value;

    if(name == "") {
        alert("Name cannot be empty");
    }
    else {
        alert("Form Submitted");
    }
}

Importance of Form Validation

  • Prevents empty input
  • Improves security
  • Improves user experience
  • Ensures correct data entry

Practice

Practice Task

Create a login form with username and password fields. Use JavaScript to check if both fields are filled.

Topic 45 - Introduction to JavaScript

Forms API [CO5]

Syllabus Topic Advanced Forms
Forms API

The Forms API provides methods and properties to work with HTML forms using JavaScript. It helps developers access form elements, validate inputs, and control form behavior.

Important Form Properties

  • value → Gets input value
  • length → Number of form elements
  • action → Form submission URL
  • method → GET or POST method

Important Form Methods

  • submit()
  • reset()
  • focus()
  • blur()

Example Using reset()

index.html
<form id="myForm">

    Name:
    <input type="text">

    <br><br>

    <button type="button" onclick="clearForm()">
        Reset
    </button>

</form>
script.js
function clearForm() {

    document.getElementById("myForm").reset();

}

Example Using focus()

script.js
document.getElementById("username").focus();

Output

The cursor automatically moves to the username field.

Advantages of Forms API

  • Easy form handling
  • Automatic validation support
  • Better user interaction
  • Faster form processing

Practice

Practice Task

Create a registration form with Name and Email fields. Add a Reset button using the reset() method.

Use focus() to automatically place the cursor in the Name field when the page loads.

Topic 46 - JS Functions

JS Functions

Syllabus Topic Template
Lecture Template

JavaScript functions are reusable blocks of code that perform a specific task. Instead of writing the same code again and again, functions allow developers to organize code into small reusable sections. Functions improve readability, reduce repetition, and make programs easier to maintain.

Overview

A function is one of the most important concepts in JavaScript. Functions help developers divide large programs into smaller manageable pieces.

Functions can:

  • Execute code when needed
  • Accept input values
  • Return results
  • Reduce duplicate code
  • Improve program structure

Functions are created using the function keyword. Once created, they can be called multiple times anywhere in the program.

Syntax

A basic JavaScript function follows this structure:

function functionName() {
    // code to execute
}
        

Example

script.js
// Creating a simple function

function greet() {
    console.log("Welcome to JavaScript Functions!");
}

// Calling the function
greet();
Output
Welcome to JavaScript Functions!
        

In the example above:

  • function greet() creates the function
  • The code inside curly braces runs when the function is called
  • greet(); executes the function

Why Functions Are Important

Imagine writing the same login validation or calculation code 20 times in a program. Functions solve this problem by allowing developers to write the logic once and reuse it everywhere.

Real World Example

Websites use functions for:

  • Login systems
  • Form validation
  • Button click events
  • Shopping cart calculations
  • Animations and effects

Practice

Practice Task

Create a function named sayHello that prints:

Hello Student!
        

Then call the function two times.

Topic 47 - JS Functions

Function Definitions

Syllabus Topic Template
Lecture Template

A function definition is the process of creating and describing what a function does. JavaScript provides different ways to define functions. Understanding function definitions is important because functions are used in almost every JavaScript application.

Overview

Function definitions tell JavaScript:

  • The name of the function
  • The code the function should execute
  • The inputs the function accepts

The most common way to define a function is using the function keyword.

Basic Function Definition
function displayMessage() {
    console.log("Learning JavaScript");
}
        

The function is only defined here. It will not execute until it is called.

Example

script.js
// Function definition

function addNumbers() {
    let a = 10;
    let b = 20;

    console.log(a + b);
}

// Function call

addNumbers();
Output
30
        

Function Naming Rules

  • Function names should be meaningful
  • Names cannot start with numbers
  • Use camelCase naming style
  • Avoid spaces in function names
Good Naming Examples
calculateTotal()
showMessage()
displayUserData()
        

Function Definition vs Function Call

Beginners often confuse defining a function with calling a function.

  • Definition: Creating the function
  • Call: Executing the function

Practice

Practice Task

Define a function called showCourse that prints:

JavaScript Masterclass
        

Then call the function once.

Topic 48 - JS Functions

Function Parameters

Syllabus Topic Template
Lecture Template

Function parameters allow data to be passed into a function. Parameters make functions flexible and reusable because the same function can work with different values.

Overview

Parameters are variables written inside the parentheses of a function. They receive values when the function is called.

Syntax
function functionName(parameter1, parameter2) {

}
        

The values passed to parameters are called arguments.

Example

script.js
// Function with parameters

function greet(name) {
    console.log("Hello " + name);
}

// Passing arguments

greet("Ali");
greet("Sara");
greet("John");
Output
Hello Ali
Hello Sara
Hello John
        

Multiple Parameters

A function can accept more than one parameter.

script.js
function add(a, b) {
    console.log(a + b);
}

add(5, 10);
add(20, 30);
Output
15
50
        

Why Parameters Are Useful

  • Make functions reusable
  • Reduce duplicate code
  • Allow dynamic input
  • Improve flexibility
Important Note

Parameters are temporary variables that only exist inside the function.

Practice

Practice Task

Create a function called multiply that accepts two parameters and prints their multiplication result.

Call the function using different numbers.

Topic 49 - JS Functions

Function Invocation

Syllabus Topic Functions
Lecture Template

Function invocation means calling or executing a function in JavaScript. A function will only run when it is invoked. Understanding function invocation is important because functions are designed to perform tasks only when needed.

Overview

After creating a function, JavaScript stores it in memory. The code inside the function does not execute automatically. To run the function, we must invoke or call it.

Basic Syntax
functionName();
        

The parentheses () are very important because they tell JavaScript to execute the function.

Example

script.js
// Function definition

function welcome() {
    console.log("Welcome to JavaScript!");
}

// Function invocation

welcome();
Output
Welcome to JavaScript!
        

How Invocation Works

  • The function is first defined
  • JavaScript stores the function in memory
  • The function runs only when invoked
  • The code inside the function executes line by line

Invoking a Function Multiple Times

One of the biggest advantages of functions is reusability. A single function can be invoked many times.

script.js
function greet() {
    console.log("Hello Student");
}

greet();
greet();
greet();
Output
Hello Student
Hello Student
Hello Student
        

Function Invocation with Arguments

Functions can also be invoked using arguments. Arguments are values passed into the function during invocation.

script.js
function greetUser(name) {
    console.log("Hello " + name);
}

greetUser("Ali");
greetUser("Sara");
Output
Hello Ali
Hello Sara
        

Important Difference

Definition vs Invocation
  • Function Definition: Creating the function
  • Function Invocation: Running the function

Common Mistake

Beginners often forget the parentheses while invoking a function.

script.js
function test() {
    console.log("Function executed");
}

// Wrong
test;

// Correct
test();

Practice

Practice Task

Create a function called showMessage that prints:

Learning Function Invocation
        

Invoke the function three times.

Then create another function that accepts a username and prints a personalized greeting message.

Topic 50 - JS Functions

Function Call

Syllabus Topic Functions
Function call() Method

In JavaScript, the call() method is used to invoke a function with a specified object. It allows one object to use another object's method.

Syntax: functionName.call(object, arg1, arg2)

Why call() is Used

  • To borrow methods from another object
  • To set the value of this
  • To reuse functions
  • To pass arguments individually

Basic Example

script.js
let person = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
};

let user = {
    firstName: "Rahul",
    lastName: "Sharma"
};

console.log(person.fullName.call(user));

Output

Rahul Sharma

call() with Arguments

script.js
function greet(city, country) {

    console.log(
        this.name + " lives in " + city + ", " + country
    );

}

let student = {
    name: "Aman"
};

greet.call(student, "Delhi", "India");

Output

Aman lives in Delhi, India

Difference Between Normal Function and call()

Normal Function call() Method
Uses default this object Allows custom this object
Arguments passed normally Arguments passed individually

Practice

Practice Task

Create an object with a method that prints full name. Use the call() method to use the same method for another object.

Topic 51 - JS Functions

Function Apply

Syllabus Topic Functions
Function apply() Method

The apply() method is similar to call(), but arguments are passed as an array.

Syntax: functionName.apply(object, [arg1, arg2])

Why apply() is Used

  • To reuse methods
  • To set custom this value
  • To pass arguments as arrays
  • Useful when arguments are already stored in arrays

Basic Example

script.js
let person = {

    fullName: function() {
        return this.firstName + " " + this.lastName;
    }

};

let employee = {

    firstName: "Riya",
    lastName: "Verma"

};

console.log(person.fullName.apply(employee));

Output

Riya Verma

apply() with Arguments

script.js
function details(city, country) {

    console.log(
        this.name + " lives in " + city + ", " + country
    );

}

let user = {
    name: "Karan"
};

details.apply(user, ["Mumbai", "India"]);

Output

Karan lives in Mumbai, India

Difference Between call() and apply()

call() apply()
Arguments passed separately Arguments passed as array
call(obj, a, b) apply(obj, [a, b])

Practice

Practice Task

Create a function that displays student information. Use the apply() method to pass values using an array.

Topic 52 - JS Functions

Function Closures [CO5]

Syllabus Topic Template
Lecture Template

A closure in JavaScript is created when a function remembers and accesses variables from its outer scope even after the outer function has finished executing. Closures are one of the most powerful features in JavaScript and are widely used in real-world applications.

Overview

Normally, local variables inside a function are destroyed after the function finishes. However, closures allow inner functions to remember those variables even later.

A closure is formed when:

  • A function is created inside another function
  • The inner function accesses variables from the outer function
  • The inner function is returned or used later
Why Closures Matter

Closures are commonly used for:

  • Data privacy
  • Creating counters
  • Maintaining state
  • Callbacks and event handling
  • Module patterns

Example

script.js
// Example of a closure

function outerFunction() {

    let counter = 0;

    function innerFunction() {
        counter++;
        console.log("Counter value: " + counter);
    }

    return innerFunction;
}

const count = outerFunction();

count();
count();
count();
Output
Counter value: 1
Counter value: 2
Counter value: 3
        

Understanding the Example

In the example above:

  • outerFunction() creates a local variable called counter
  • innerFunction() accesses the counter variable
  • The inner function is returned and stored in count
  • Even after outerFunction() finishes, the inner function still remembers counter

This memory behavior is called a closure.

Real World Analogy

Simple Analogy

Think of a closure like a backpack. When a function leaves its original environment, it carries its required variables inside the backpack and can still use them later.

Another Example

script.js
// Closure with user data

function userProfile(username) {

    return function() {
        console.log("Logged in user: " + username);
    };
}

const profile = userProfile("Alex");

profile();
Output
Logged in user: Alex
        

Advantages of Closures

  • Provides data protection
  • Keeps variables private
  • Allows state preservation
  • Improves code organization
  • Useful in asynchronous programming

Important Note

Remember

Closures do not copy variables. They keep a reference to the original variables from the outer scope.

Practice

Practice Task

Create a function called bankAccount that:

  • Creates a variable named balance
  • Returns an inner function
  • Increases the balance every time the inner function is called
  • Prints the updated balance

Call the returned function multiple times and observe how the balance value is remembered.