JS Introduction
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
// 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
Create a JavaScript file that shows an alert saying "Hello World" and prints your name in the browser console.
Where To
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
<!-- Internal JavaScript -->
<script>
alert("Hello from JavaScript");
</script>
This method is useful for small projects or quick testing.
External JavaScript
<!-- 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
Create an HTML file and connect an external JavaScript file named script.js. Print a message in the console.
Output
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
// Change HTML content
document.getElementById("demo").innerHTML = "Hello JavaScript";
This method changes the content of an HTML element.
Using document.write()
// Write directly to page
document.write("Learning JavaScript");
document.write() is mainly used for testing and simple examples.
Using alert()
// Popup message
alert("Welcome!");
The alert() function displays a popup dialog box in the browser.
Using console.log()
// 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
Create a webpage that uses all four JavaScript output methods to display different messages.
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
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.
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.
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.
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.
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.
let i = 0; while (i < 3) { console.log(i); i++; };
Practice
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
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
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.
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.
if (true) { console.log("Inside block"); }
Whitespace & Indentation
Spaces and line breaks improve readability. Proper indentation makes code easier to understand and debug.
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.
let x = 10; let y = 20; console.log(x + y);
Practice
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
Comments
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 //.
// Store user age let age = 20; // Print age to console console.log(age);
Multi-Line Comments
Multi-line comments start with /* and end with */.
/* 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.
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.
// Apply 10% discount for premium members
total = total - (total * 0.10);
Practice
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
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 methodlet— modern and recommendedconst— used for constant values
Declaring Variables
// 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
// Updating values
let score = 10;
score = 20;
console.log(score);
Variables declared with let can be updated later.
Constants
// Constant value
const pi = 3.14;
console.log(pi);
Variables declared with const cannot be reassigned after creation.
Practice
Create variables for your name, age, and favorite programming language. Print all values using console.log().
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
// 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
// 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
Create variables and use arithmetic, comparison, and logical operators to test different conditions.
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
// 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
// Modulus operator
let num = 10;
console.log(num % 3);
The modulus operator returns the remainder after division.
Increment and Decrement
// 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.
// Operator precedence
let result = 5 + 2 * 3;
console.log(result);
Multiplication happens before addition, so the result will be 11.
Practice
Create a simple calculator that performs addition, subtraction, multiplication, and division using JavaScript variables.
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:
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
// 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.
let message = "Hello"; message += " World"; console.log(message);
Increment & Decrement
JavaScript provides special operators for increasing or decreasing values by 1.
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.
let total = 0; total += 200; total += 150; total += 50; console.log("Final Total:", total);
Practice
Create a variable called salary with value 1000. Add a bonus of 500, subtract tax of 200, then print the final salary.
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
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.
let fruits = ["Apple", "Mango", "Banana"]; console.log(fruits[0]); console.log(fruits.length);
Objects
Objects store data in key-value pairs.
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.
let num = "100"; console.log(Number(num) + 50); let value = 25; console.log(String(value));
Practice
Create variables for your name, age, and whether you are a student. Print their values and data types using typeof.
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 greet() { console.log("Welcome to JavaScript"); } greet();
Functions with Parameters
Parameters allow functions to receive data.
function greet(name) { console.log("Hello " + name); } greet("Ahmed"); greet("Sara");
Return Statement
The return keyword sends a value back from the function.
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.
const square = (num) => {
return num * num;
};
console.log(square(4));
Default Parameters
Default parameters are used when no argument is passed.
function welcome(user = "Guest") { console.log("Welcome " + user); } welcome(); welcome("Ali");
Practice
Create a function that accepts two numbers and prints their multiplication table result.
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
// 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
// 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
// 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
// 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
Create an object called book with properties for title, author, and price. Print all values in the console.
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
<!-- 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
<!-- 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
// 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
Create a button that changes the background color of the webpage when clicked.
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
// Creating strings
let firstName = "Ahmed";
let city = 'Delhi';
let message = `Welcome`;
console.log(firstName);
console.log(city);
console.log(message);
String Concatenation
// Combining strings
let first = "Hello";
let second = "World";
let result = first + " " + second;
console.log(result);
The + operator combines strings together.
Template Literals
// 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
// String methods
let text = "JavaScript";
console.log(text.length);
console.log(text.toUpperCase());
console.log(text.includes("Script"));
Practice
Create a program that asks for a user's name and displays a welcome message using template literals.
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
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
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.
let sentence = "HTML CSS JavaScript"; let words = sentence.split(" "); console.log(words);
Template Literals
Template literals use backticks and allow variables inside strings using ${}.
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.
console.log("Hello\nWorld"); console.log("JavaScript\tTutorial"); console.log("She said \"Hello\"");
Practice
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.
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
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
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.
console.log(Infinity); console.log(-Infinity); console.log(NaN);
Converting Strings to Numbers
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.
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
Create two number variables and perform all arithmetic operations on them. Also print the square root of one number using the Math object.
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
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.
let price = 199.4567;
console.log(price.toFixed(2));
Checking Numeric Values
You can check whether a value is numeric using isNaN().
console.log(isNaN(100));
console.log(isNaN("JavaScript"));
Parsing Numbers
JavaScript can extract numbers from strings.
console.log(parseInt("50px")); console.log(parseFloat("99.99 dollars"));
Practice
Create a decimal number variable. Print it with 1, 2, and 3 decimal places using toFixed(). Then convert the number into a string.
Arrays
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
let fruits = ["Apple", "Banana", "Mango"]; console.log(fruits[0]); console.log(fruits[1]); console.log(fruits[2]);
Apple
Banana
Mango
Creating Arrays
Arrays are created using square brackets [].
let numbers = [10, 20, 30, 40]; console.log(numbers);
Different Types of Data in Arrays
JavaScript arrays can store different types of values together.
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.
let colors = ["Red", "Blue", "Green"]; colors[1] = "Yellow"; console.log(colors);
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.
let subjects = ["Math", "Science", "English"]; console.log(subjects.length);
3
Example
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
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
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.
let fruits = ["Apple", "Banana"];
fruits.push("Mango");
console.log(fruits);
pop()
The pop() method removes the last element from an array.
let fruits = ["Apple", "Banana", "Mango"]; fruits.pop(); console.log(fruits);
shift()
The shift() method removes the first element from an array.
let colors = ["Red", "Blue", "Green"]; colors.shift(); console.log(colors);
unshift()
The unshift() method adds a new element at the beginning of the array.
let colors = ["Blue", "Green"];
colors.unshift("Red");
console.log(colors);
includes()
The includes() method checks whether a value exists inside an array.
let subjects = ["Math", "Science", "English"];
console.log(subjects.includes("Math"));
true
indexOf()
The indexOf() method returns the index position of a value.
let animals = ["Cat", "Dog", "Lion"];
console.log(animals.indexOf("Dog"));
1
Example
let numbers = [10, 20, 30]; numbers.push(40); numbers.pop(); console.log(numbers); numbers.unshift(5); console.log(numbers);
Practice
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()
Array Sort
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.
let fruits = ["Mango", "Apple", "Banana"]; fruits.sort(); console.log(fruits);
["Apple", "Banana", "Mango"]
Sorting Numbers
Sorting numbers can sometimes give unexpected results because JavaScript converts numbers into strings.
let numbers = [100, 20, 5, 40]; numbers.sort(); console.log(numbers);
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.
let numbers = [100, 20, 5, 40];
numbers.sort(function(a, b){
return a - b;
});
console.log(numbers);
[5, 20, 40, 100]
Descending Order
To sort numbers in descending order, reverse the subtraction.
let marks = [45, 90, 20, 70];
marks.sort(function(a, b){
return b - a;
});
console.log(marks);
Example
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
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
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.
let fruits = ["Apple", "Banana", "Mango"];
for(let i = 0; i < fruits.length; i++){
console.log(fruits[i]);
}
Apple
Banana
Mango
Using for...of Loop
The for...of loop is a simpler way to iterate through array values.
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.
let numbers = [10, 20, 30];
numbers.forEach(function(value){
console.log(value);
});
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.
let numbers = [1, 2, 3];
let result = numbers.map(function(value){
return value * 2;
});
console.log(result);
[2, 4, 6]
filter() Method
The filter() method creates a new array containing only matching elements.
let ages = [12, 18, 25, 10, 30];
let adults = ages.filter(function(age){
return age >= 18;
});
console.log(adults);
[18, 25, 30]
Difference Between map() and filter()
- map() modifies every element
- filter() selects specific elements
- Both methods return a new array
Example
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
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
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.
let today = new Date(); console.log(today);
Getting Current Year
The getFullYear() method returns the current year.
let date = new Date(); console.log(date.getFullYear());
Getting Current Month
The getMonth() method returns the month number.
Months start from 0 in JavaScript. January is 0 and December is 11.
let date = new Date(); console.log(date.getMonth());
Getting Current Date
The getDate() method returns the current day of the month.
let date = new Date(); console.log(date.getDate());
Getting Current Time
We can also get hours, minutes, and seconds.
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().
let birthday = new Date(2005, 5, 15); console.log(birthday);
Example
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
Create a program that:
- Displays current year
- Displays current month
- Displays current date
- Displays current hours and minutes
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.
let today = new Date(); console.log(today.toDateString());
toTimeString()
The toTimeString() method displays only the time portion.
let today = new Date(); console.log(today.toTimeString());
toLocaleDateString()
The toLocaleDateString() method formats the date according to local settings.
let today = new Date(); console.log(today.toLocaleDateString());
toLocaleTimeString()
The toLocaleTimeString() method formats time according to local settings.
let today = new Date(); console.log(today.toLocaleTimeString());
Full Date and Time
The toLocaleString() method displays both date and time together.
let today = new Date(); console.log(today.toLocaleString());
5/27/2026, 10:30:45 AM
Example
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
Create a program that displays:
- Current date only
- Current time only
- Full local date and time
- Date using toDateString()
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.
let date = new Date(); console.log(date.getFullYear());
2026
getMonth()
The getMonth() method returns the month number.
Months start from 0 in JavaScript. January is 0 and December is 11.
let date = new Date(); console.log(date.getMonth());
getDate()
The getDate() method returns the day of the month.
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
let date = new Date(); console.log(date.getDay());
getHours()
The getHours() method returns the current hour.
let time = new Date(); console.log(time.getHours());
getMinutes()
The getMinutes() method returns current minutes.
let time = new Date(); console.log(time.getMinutes());
getSeconds()
The getSeconds() method returns current seconds.
let time = new Date(); console.log(time.getSeconds());
Example
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
Create a JavaScript program that:
- Displays current year
- Displays current month
- Displays current day
- Displays current hours and minutes
- Displays current seconds
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.
let date = new Date(); date.setFullYear(2030); console.log(date);
setMonth()
The setMonth() method changes the month value.
Months start from 0. January is 0 and December is 11.
let date = new Date(); date.setMonth(11); console.log(date);
setDate()
The setDate() method changes the day of the month.
let date = new Date(); date.setDate(15); console.log(date);
setHours()
The setHours() method changes the hour value.
let time = new Date(); time.setHours(10); console.log(time);
setMinutes()
The setMinutes() method changes minutes.
let time = new Date(); time.setMinutes(30); console.log(time);
setSeconds()
The setSeconds() method changes seconds.
let time = new Date(); time.setSeconds(45); console.log(time);
Example
let customDate = new Date(); customDate.setFullYear(2028); customDate.setMonth(5); customDate.setDate(20); customDate.setHours(9); customDate.setMinutes(15); console.log(customDate);
Practice
Create a Date object and:
- Change the year
- Change the month
- Change the date
- Change the hours
- Change the minutes
Math
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.
console.log(Math.round(4.6)); console.log(Math.round(4.3));
5
4
Math.ceil()
The Math.ceil() method rounds a number upward.
console.log(Math.ceil(4.1));
Math.floor()
The Math.floor() method rounds a number downward.
console.log(Math.floor(4.9));
Math.max()
The Math.max() method returns the largest value.
console.log(Math.max(10, 20, 50, 5));
Math.min()
The Math.min() method returns the smallest value.
console.log(Math.min(10, 20, 50, 5));
Math.random()
The Math.random() method generates a random number between 0 and 1.
console.log(Math.random());
Math.pow()
The Math.pow() method calculates power values.
console.log(Math.pow(2, 3));
8
Math.sqrt()
The Math.sqrt() method returns the square root of a number.
console.log(Math.sqrt(64));
8
Example
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
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
Random
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.
The number generated will always be less than 1.
Basic Random Number
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.
let number = Math.floor(Math.random() * 10) + 1; console.log(number);
Output Example
7
Dice Roll Example
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
Create a program that generates a random number between 1 and 100.
Bonus: Create a simple dice rolling simulator.
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
let isStudent = true; let isLoggedIn = false; console.log(isStudent); console.log(isLoggedIn);
Output
true false
Boolean from Comparison
console.log(10 > 5); console.log(3 == 7);
Output
true false
Boolean in If Statement
let raining = true;
if (raining) {
console.log("Take an umbrella");
}
Falsy Values in JavaScript
- false
- 0
- "" (empty string)
- null
- undefined
- NaN
Practice
Create a Boolean variable named isAdmin and print its value.
Also check whether 20 is greater than 15.
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
console.log(10 > 5); console.log(5 < 2); console.log(10 == "10"); console.log(10 === "10");
Output
true false true false
Difference Between == and ===
== compares only values while === compares both value and data type.
Using Comparisons in Conditions
let age = 18;
if (age >= 18) {
console.log("Eligible to vote");
}
Practice
Write a program that checks whether a number is greater than 50.
Also compare two strings using == and ===.
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
if(condition){
// code to execute
}
Example 1 — Simple if
let age = 20;
if(age >= 18){
console.log("You can vote");
}
Output
You can vote
Example 2 — if...else
let number = 5;
if(number % 2 === 0){
console.log("Even Number");
}else{
console.log("Odd Number");
}
Output
Odd Number
Example 3 — else if
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
Write a JavaScript program that checks whether a number is positive, negative, or zero using if...else if...else.
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
switch(expression){
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
Example
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
Create a switch program that displays month names based on numbers from 1 to 12.
Loop For
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
for(initialization; condition; increment){
// code block
}
Example 1 — Print Numbers
for(let i = 1; i <= 5; i++){
console.log(i);
}
Output
1
2
3
4
5
Example 2 — Even Numbers
for(let i = 2; i <= 10; i += 2){
console.log(i);
}
Output
2
4
6
8
10
Loop Flow
- Initialization runs once
- Condition is checked
- Code executes if condition is true
- Increment/decrement happens
- Condition is checked again
Practice
Write a for loop that prints the multiplication table of 5.
Loop While
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
while(condition){
// code block
}
Example 1 — Print Numbers
let i = 1;
while(i <= 5){
console.log(i);
i++;
}
Output
1
2
3
4
5
Example 2 — Even Numbers
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
Write a while loop that prints numbers from 10 to 1 in reverse order.
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
break;
Example — break in for Loop
for(let i = 1; i <= 10; i++){
if(i === 5){
break;
}
console.log(i);
}
Output
1
2
3
4
How it Works
- Loop starts from 1
- Numbers print normally
- When i becomes 5, break runs
- The loop stops immediately
break in switch
In switch statements, break prevents execution of the next cases.
Practice
Write a loop that prints numbers from 1 to 20 and stops when the number becomes 12.
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
let num = "100"; console.log(Number(num));
Output
100
Convert Number to String
let number = 50; console.log(String(number));
Output
50
Implicit Conversion Example
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
Convert the string "250" into a number and add 50 to it.
Bitwise
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
// 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
Create two variables and perform all bitwise operators on them.
Display the results using console.log().
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 existsmatch()→ returns matched valuesreplace()→ replaces textsearch()→ returns match position
Example
// 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
Create a regular expression to check whether a string contains the word "HTML".
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
// 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
trycontains risky code.catchruns if an error occurs.finallyalways executes.
Practice
Create a program using try and catch
to handle an undefined variable error.
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
// 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
nameis global and can be used anywhere.ageworks only inside the function.cityworks only inside the block.
Practice
Create variables using var, let,
and const inside different scopes and test where
they can be accessed.
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
// 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
Create examples using var, let,
and const to observe hoisting behavior.
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
// 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
Enable strict mode and create examples that show errors for undeclared variables and duplicate parameters.
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
{
"name": "Rahul",
"age": 20,
"course": "BCA",
"isStudent": true
}
JSON.parse()
JSON.parse() converts JSON string into a JavaScript object.
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.
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
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().
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
<form>
Name:
<input type="text" id="username">
<br><br>
<button onclick="showName()" type="button">
Submit
</button>
</form>
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
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
Create a login form with username and password fields. Use JavaScript to check if both fields are filled.
Forms API [CO5]
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 valuelength→ Number of form elementsaction→ Form submission URLmethod→ GET or POST method
Important Form Methods
submit()reset()focus()blur()
Example Using reset()
<form id="myForm">
Name:
<input type="text">
<br><br>
<button type="button" onclick="clearForm()">
Reset
</button>
</form>
function clearForm() {
document.getElementById("myForm").reset();
}
Example Using focus()
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
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.
JS Functions
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.
A basic JavaScript function follows this structure:
function functionName() {
// code to execute
}
Example
// Creating a simple function function greet() { console.log("Welcome to JavaScript Functions!"); } // Calling the function greet();
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.
Websites use functions for:
- Login systems
- Form validation
- Button click events
- Shopping cart calculations
- Animations and effects
Practice
Create a function named sayHello that prints:
Hello Student!
Then call the function two times.
Function Definitions
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.
function displayMessage() {
console.log("Learning JavaScript");
}
The function is only defined here. It will not execute until it is called.
Example
// Function definition function addNumbers() { let a = 10; let b = 20; console.log(a + b); } // Function call addNumbers();
30
Function Naming Rules
- Function names should be meaningful
- Names cannot start with numbers
- Use camelCase naming style
- Avoid spaces in function names
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
Define a function called showCourse that prints:
JavaScript Masterclass
Then call the function once.
Function Parameters
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.
function functionName(parameter1, parameter2) {
}
The values passed to parameters are called arguments.
Example
// Function with parameters function greet(name) { console.log("Hello " + name); } // Passing arguments greet("Ali"); greet("Sara"); greet("John");
Hello Ali
Hello Sara
Hello John
Multiple Parameters
A function can accept more than one parameter.
function add(a, b) {
console.log(a + b);
}
add(5, 10);
add(20, 30);
15
50
Why Parameters Are Useful
- Make functions reusable
- Reduce duplicate code
- Allow dynamic input
- Improve flexibility
Parameters are temporary variables that only exist inside the function.
Practice
Create a function called multiply that accepts two parameters
and prints their multiplication result.
Call the function using different numbers.
Function Invocation
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.
functionName();
The parentheses () are very important because they tell JavaScript
to execute the function.
Example
// Function definition function welcome() { console.log("Welcome to JavaScript!"); } // Function invocation welcome();
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.
function greet() {
console.log("Hello Student");
}
greet();
greet();
greet();
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.
function greetUser(name) {
console.log("Hello " + name);
}
greetUser("Ali");
greetUser("Sara");
Hello Ali
Hello Sara
Important Difference
- Function Definition: Creating the function
- Function Invocation: Running the function
Common Mistake
Beginners often forget the parentheses while invoking a function.
function test() {
console.log("Function executed");
}
// Wrong
test;
// Correct
test();
Practice
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.
Function Call
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
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
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
Create an object with a method that prints full name.
Use the call() method to use the same method for another object.
Function Apply
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
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
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
Create a function that displays student information.
Use the apply() method to pass values using an array.
Function Closures [CO5]
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
Closures are commonly used for:
- Data privacy
- Creating counters
- Maintaining state
- Callbacks and event handling
- Module patterns
Example
// 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();
Counter value: 1
Counter value: 2
Counter value: 3
Understanding the Example
In the example above:
outerFunction()creates a local variable calledcounterinnerFunction()accesses thecountervariable- The inner function is returned and stored in
count - Even after
outerFunction()finishes, the inner function still rememberscounter
This memory behavior is called a closure.
Real World 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
// Closure with user data
function userProfile(username) {
return function() {
console.log("Logged in user: " + username);
};
}
const profile = userProfile("Alex");
profile();
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
Closures do not copy variables. They keep a reference to the original variables from the outer scope.
Practice
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.