LAST UPDATED: August 25, 2025
JavaScript Hello World
Hello Everyone!
In this tutorial, we will learn how to write a basic Hello World program in JavaScript.
// Example: Display Hello World in browser console
console.log("Hello World! Welcome to Tutorials!");
Explanation:
Let's break down what we have done in the above code.
1. console.log()
The console.log()
method prints messages to the browser console.
It is similar to cout
in C++ or printf
in C.
2. Strings in JavaScript
Text inside quotes (single or double) is treated as a string. In the example,
"Hello World! Welcome to Tutorials!"
is a string.
3. Execution in Browser
You can run this code in the browser console:
Right-click → Inspect → Console → Paste code → Enter
Introduction to JavaScript
1.1 What is JS?
JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming
language.
It is widely used for web development to make webpages interactive.
JavaScript is an essential part of web applications alongside HTML and CSS.
// Example: Display a message
console.log("JavaScript is fun!");
Task: Open your browser console and try printing your name using
console.log()
.
1.2 Features of JavaScript
- Lightweight and interpreted
- Client-side execution (mostly)
- Dynamic typing
- Object-oriented and functional capabilities
- Event-driven programming
- Cross-platform support
Task: Create an HTML page and print each feature inside an alert using
JavaScript.
<script>
alert("JavaScript Feature 1: Lightweight");
alert("JavaScript Feature 2: Client-side execution");
</script>
1.3 Syntax
JavaScript syntax is similar to C, C++, and Java. It includes variables, operators, loops,
and functions.
// Variable
let message = "Hello JS!";
// Function
function greet(name) {
console.log("Hello, " + name);
}
greet("Aman");
1.4 JavaScript in Browser
JavaScript can run directly in the browser. You can:
- Use
<script>
tag in HTML
- Run code in browser console
- Link external JS files using
<script src="file.js"></script>
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<script>
document.write("This is JavaScript running in the browser!");
</script>
</body>
</html>
1.5 Setting up Environment
You don't need any heavy IDE to start JavaScript:
- Any modern browser (Chrome, Firefox, Edge)
- Code editor like VS Code, Sublime Text, or Notepad++
- Optional: Node.js to run JS outside the browser
Task: Create a simple HTML page, include a JS file, and display a welcome
message.
<!DOCTYPE html>
<html>
<body>
<h1>Welcome Page</h1>
<script src="welcome.js"></script>
</body>
</html>
// welcome.js
console.log("Welcome to JavaScript Learning!");
JavaScript Output
2.1 console.log
The console.log()
method outputs messages to the browser console.
It is mainly used for debugging and checking values during development.
// Example
let name = "Aman";
console.log("Hello, " + name);
2.2 alert
The alert()
method displays a popup alert box with a message to the user.
It stops the execution until the user closes the alert.
// Example
alert("Welcome to JavaScript!");
Task: Display your name and age in an alert box.
2.3 document.write
The document.write()
method writes text directly to the HTML document.
It is mostly used for simple demonstrations but is not recommended for modern web development.
// Example
document.write("Hello, World!");
Task: Write your favorite color using document.write()
.
Mini Project: Create a script that writes a list of 5 hobbies on the HTML page using document.write()
.
2.4 innerHTML
The innerHTML
property allows you to change the content of an HTML element dynamically.
This is the preferred way to display output in modern web applications.
<!DOCTYPE html>
<html>
<body>
<h1 id="demo">Hello</h1>
<script>
document.getElementById("demo").innerHTML = "Hello, JavaScript!";
</script>
</body>
</html>
Task: Change the text of a paragraph using innerHTML
.
JavaScript Comments
Comments in JavaScript are used to explain the code, make it more readable, and prevent execution of certain lines. They are ignored by the JavaScript engine.
3.1 Single-line Comments
Single-line comments are used to write brief explanations or notes in a single line.
They start with //
.
// This is a single-line comment
let x = 5; // You can also comment at the end of a line
console.log(x);
3.2 Multi-line Comments
Multi-line comments are used to write longer explanations or temporarily disable blocks of code.
They start with /*
and end with */
.
/* This is a multi-line comment
It can span multiple lines
Very useful for explaining complex logic */
let y = 10;
console.log(y);
JavaScript Variables
Variables in JavaScript are containers to store data values. You can store numbers, strings, objects, arrays, and more. JavaScript provides three ways to declare variables: var
, let
, and const
.
4.1 var
var
is the oldest way to declare variables in JavaScript. Variables declared with var
are function-scoped and can be redeclared.
// Using var
var name = "John";
console.log(name);
var name = "Doe"; // redeclaration allowed
console.log(name);
Task: Declare a variable using var
and change its value. Log both values to the console.
4.2 let
let
is block-scoped, meaning it is only accessible inside the block it is defined. It cannot be redeclared in the same scope.
// Using let
let age = 25;
console.log(age);
age = 30; // updating value is allowed
console.log(age);
// let age = 35; // Error: cannot redeclare in same scope
Task: Create a block (e.g., inside curly braces {}) and declare a variable with let
. Try accessing it outside the block and see the result.
4.3 const
const
is used to declare variables whose value should not change. It is also block-scoped and must be initialized during declaration.
// Using const
const pi = 3.14;
console.log(pi);
// pi = 3.14159; // Error: assignment to constant variable
Task: Declare a constant variable for your birth year. Try changing it and observe the error.
JavaScript Data Types
Data types define the kind of values we can store and manipulate in JavaScript.
JavaScript has two main categories of data types: Primitive and Non-Primitive (Reference).
Additionally, we often work with type conversion and the typeof
operator.
5.1 Primitive Data Types
Primitive data types are the most basic types in JavaScript. They are immutable and stored by value.
The primitive data types are:
String
– Represents text
Number
– Represents integers and floating-point numbers
Boolean
– Represents true
or false
Null
– Represents an intentional "empty" value
Undefined
– A variable declared but not assigned a value
Symbol
– Represents unique values (introduced in ES6)
BigInt
– For very large integers (introduced in ES2020)
let name = "Alice"; // String
let age = 25; // Number
let isStudent = true; // Boolean
let score = null; // Null
let city; // Undefined
let id = Symbol("id"); // Symbol
let bigNum = 12345678901234567890n; // BigInt
Task: Declare variables of each primitive type and log them to the console.
5.2 Non-Primitive (Reference) Data Types
Non-primitive types are objects and are stored by reference. They include:
Object
– Key-value pairs
Array
– Ordered list of values
Function
– Reusable block of code
let person = { name: "Bob", age: 30 }; // Object
let colors = ["red", "green", "blue"]; // Array
function greet() { // Function
console.log("Hello World!");
}
5.3 Type Conversion
JavaScript automatically converts data types in some cases (type coercion).
We can also explicitly convert types:
let num = "42";
console.log(Number(num)); // String → Number
console.log(String(100)); // Number → String
console.log(Boolean(0)); // 0 → false, non-zero → true
Task: Take a string number like "123"
and convert it to a number, then back to a string.
5.4 typeof Operator
The typeof
operator is used to check the type of a variable.
console.log(typeof "hello"); // "string"
console.log(typeof 123); // "number"
console.log(typeof true); // "boolean"
console.log(typeof {}); // "object"
console.log(typeof []); // "object" (arrays are objects)
console.log(typeof null); // "object" (a known quirk in JS)
console.log(typeof undefined); // "undefined"
Task: Use typeof
on all your variables from the above examples and observe the results.
JavaScript Operators
Operators are symbols that perform operations on variables and values.
JavaScript provides a wide variety of operators for arithmetic, assignment, comparison, logical operations, and more.
6.1 Arithmetic Operators
Arithmetic operators are used for mathematical calculations.
let a = 10, b = 3;
console.log(a + b); // 13 (Addition)
console.log(a - b); // 7 (Subtraction)
console.log(a * b); // 30 (Multiplication)
console.log(a / b); // 3.33 (Division)
console.log(a % b); // 1 (Modulus - Remainder)
console.log(a ** b); // 1000 (Exponentiation)
Task: Write a program that calculates area and perimeter of a rectangle.
6.2 Assignment Operators
Used to assign values to variables.
let x = 10;
x += 5; // 15
x -= 3; // 12
x *= 2; // 24
x /= 4; // 6
x %= 4; // 2
Task: Start with x = 50
and perform all assignment operators step by step.
6.3 Comparison Operators
Used to compare two values and return a boolean (true
/false
).
console.log(5 == "5"); // true (loose equality)
console.log(5 === "5"); // false (strict equality)
console.log(10 != 5); // true
console.log(10 > 5); // true
console.log(10 < 5); // false
console.log(10 >= 10); // true
console.log(10 <= 5); // false
6.4 Logical Operators
Used to combine or invert boolean values.
let age = 20, hasID = true;
console.log(age >= 18 && hasID); // true (AND)
console.log(age >= 18 || hasID); // true (OR)
console.log(!hasID); // false (NOT)
6.5 Relational Operators
Relational operators check the relationship between two values (similar to comparison).
Example: >
, <
, >=
, <=
.
console.log("apple" > "banana"); // false (lexical order)
console.log("zebra" > "apple"); // true
6.6 Bitwise Operators
Work at the binary level (rare in JS, but useful for performance).
console.log(5 & 1); // 1 (AND)
console.log(5 | 1); // 5 (OR)
console.log(5 ^ 1); // 4 (XOR)
console.log(~5); // -6 (NOT)
console.log(5 << 1); // 10 (Left shift)
console.log(5 >> 1); // 2 (Right shift)
6.7 Unary Operators
Work with a single operand.
let y = 5;
console.log(+y); // 5
console.log(-y); // -5
console.log(++y); // 6 (increment)
console.log(--y); // 5 (decrement)
6.8 Ternary Operator
A shorthand for if...else
.
let score = 80;
let result = (score >= 50) ? "Pass" : "Fail";
console.log(result); // Pass
Task: Check if a number is even or odd using ternary.
6.9 Spread & Rest Operators
Both use ...
but have different roles.
// Spread
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];
console.log(newArr);
// Rest
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
6.10 typeof & instanceof
typeof
→ returns type of variable.
instanceof
→ checks if an object is instance of a class.
console.log(typeof "Hello"); // string
console.log(typeof 123); // number
let arr2 = [];
console.log(arr2 instanceof Array); // true
6.11 Nullish Coalescing (??)
Returns the right-hand value only if the left-hand side is null
or undefined
.
let username = null;
console.log(username ?? "Guest"); // Guest
6.12 Optional Chaining (?.)
Prevents errors when accessing properties of null
or undefined
.
let user = { profile: { name: "Alice" } };
console.log(user.profile?.name); // Alice
console.log(user.contact?.email); // undefined (no error)
Mini Project
Build a Grading System:
Ask the user for a score and assign a grade using operators.
let score2 = 72;
let grade = (score2 >= 90) ? "A" :
(score2 >= 80) ? "B" :
(score2 >= 70) ? "C" :
(score2 >= 60) ? "D" : "F";
console.log(`Score: ${score2}, Grade: ${grade}`);
JavaScript Conditional Statements
Conditional statements allow you to execute different code blocks based on certain conditions.
JavaScript provides if
, if-else
, else-if
, and switch
statements for decision-making.
7.1 if Statement
The if
statement executes a block of code if a specified condition is true.
let num = 10;
if (num > 5) {
console.log("Number is greater than 5");
}
Task: Check if a number is positive.
7.2 if-else Statement
The if-else
statement executes one block if the condition is true, and another block if it is false.
let age = 17;
if (age >= 18) {
console.log("You can vote");
} else {
console.log("You are too young to vote");
}
Task: Write a program to check if a number is even or odd using if-else
.
7.3 else-if Statement
The else-if
statement allows multiple conditions to be checked in sequence.
let marks = 75;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else if (marks >= 60) {
console.log("Grade C");
} else {
console.log("Fail");
}
Task: Write a program to assign grades A, B, C, D, F based on score ranges.
7.4 switch Statement
The switch
statement evaluates an expression and executes code blocks based on matching cases.
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName); // Wednesday
Task: Write a program to display month names based on month number using switch
.
Mini Project: Simple Calculator
Create a simple calculator that takes two numbers and an operator (+
, -
, *
, /
)
from the user and performs the calculation using if-else
or switch
.
let num1 = 10;
let num2 = 5;
let operator = "+";
let result;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
result = "Invalid operator";
}
console.log("Result:", result); // 15
JavaScript Looping Statements
Loops are used to execute a block of code repeatedly until a specified condition evaluates to false.
JavaScript provides several types of loops: for
, while
, do...while
,
for...in
, and for...of
.
8.1 for Loop
The for
loop executes a block of code a known number of times.
for (let i = 1; i <= 5; i++) {
console.log("Number:", i);
}
Task: Print the first 10 natural numbers using a for
loop.
8.2 while Loop
The while
loop executes a block of code as long as a specified condition is true.
let i = 1;
while (i <= 5) {
console.log("Number:", i);
i++;
}
Task: Display numbers from 1 to 10 using while
loop.
8.3 do...while Loop
The do...while
loop executes the block first and then checks the condition.
This ensures the loop runs at least once.
let i = 1;
do {
console.log("Number:", i);
i++;
} while (i <= 5);
Task: Print numbers from 10 down to 1 using do...while
loop.
8.4 for...in Loop
The for...in
loop iterates over the keys (property names) of an object.
const person = {name: "John", age: 25, city: "Delhi"};
for (let key in person) {
console.log(key + ":", person[key]);
}
Task: Loop through an object of students and print their names and marks.
8.5 for...of Loop
The for...of
loop iterates over the values of an iterable object (like arrays, strings).
const fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
Task: Print each character of a string using for...of
.
Mini Project: Multiplication Table
Create a multiplication table for a given number using for
or while
loops.
let number = 7;
for (let i = 1; i <= 10; i++) {
console.log(number + " x " + i + " = " + number * i);
}
JavaScript Jumping Statements
Jumping statements are used to alter the normal flow of loops or functions in JavaScript.
They allow you to exit loops early, skip iterations, or return values from functions.
9.1 break Statement
The break
statement is used to exit a loop or a switch
statement immediately.
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break; // stops the loop when i is 5
}
console.log(i);
}
Output: 1 2 3 4
Task: Use a break
statement to stop printing numbers when a multiple of 7 is encountered.
9.2 continue Statement
The continue
statement skips the current iteration of the loop and moves to the next iteration.
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue; // skips even numbers
}
console.log(i);
}
Output: 1 3 5 7 9
Task: Use continue
to skip negative numbers in an array.
9.3 return Statement
The return
statement is used to exit a function and optionally return a value.
function sum(a, b) {
return a + b; // returns the sum of a and b
}
let result = sum(5, 7);
console.log(result);
Output: 12
Task: Create a function that returns the largest number in an array using return
.
Mini Project: Number Filter
Create a program that loops through an array of numbers. Skip all odd numbers (continue
),
stop the loop if a number greater than 50 is found (break
), and display the sum of processed numbers using a function (return
).
const numbers = [2, 5, 8, 15, 22, 55, 3];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 !== 0) continue;
if (numbers[i] > 50) break;
sum += numbers[i];
}
function displaySum(total) {
return "Sum: " + total;
}
console.log(displaySum(sum));
JavaScript Functions
Functions in JavaScript are blocks of reusable code designed to perform a particular task.
Functions help in organizing code, reducing repetition, and improving readability.
10.1 Function Declaration & Expression
Function Declaration:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
Function Expression:
const greet = function(name) {
console.log("Hello, " + name + "!");
};
greet("Bob");
Task: Write a function declaration and expression to multiply two numbers.
10.2 Parameters, Arguments & Default Parameters
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet(); // Hello, Guest!
greet("Alice"); // Hello, Alice!
Task: Create a function to calculate the area of a rectangle with default width = 10 and height = 5.
10.3 Return Values
function add(a, b) {
return a + b;
}
let result = add(5, 7);
console.log(result); // 12
Task: Write a function that returns the largest number in an array.
10.4 Anonymous Functions
const greet = function(name) {
console.log("Hello, " + name);
};
greet("Alice");
Task: Create an anonymous function to check if a number is even.
10.5 Arrow Functions
const greet = (name) => console.log("Hello, " + name);
greet("Bob");
Task: Convert a function expression to an arrow function that adds two numbers.
10.6 Recursive Functions
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
Task: Write a recursive function to calculate the sum of numbers from 1 to n.
10.7 Callback Functions
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
greet("Alice", function() {
console.log("This is a callback function!");
});
Task: Use a callback function to filter numbers greater than 10 from an array.
10.8 IIFE (Immediately Invoked Function Expression)
(function() {
console.log("IIFE executed immediately!");
})();
Task: Create an IIFE that calculates and logs the square of a number.
10.9 Higher Order Functions
A higher-order function is a function that takes another function as an argument or returns a function.
function multiplier(factor) {
return function(x) {
return x * factor;
};
}
const double = multiplier(2);
console.log(double(5)); // 10
Task: Create a higher-order function that takes an array and a callback to process its elements.
10.10 Built-in Functions
JavaScript has many built-in functions such as alert()
, parseInt()
, parseFloat()
, isNaN()
, setTimeout()
, and Math
methods.
console.log(Math.sqrt(16)); // 4
console.log(parseInt("42")); // 42
console.log(isNaN("Hello")); // true
Task: Use at least three built-in functions to manipulate numbers and strings in a program.
Mini Project: Calculator
Create a simple calculator using functions that can perform addition, subtraction, multiplication, and division. Use higher-order functions for operations, default parameters for missing input, and arrow functions wherever possible.
const add = (a, b = 0) => a + b;
const subtract = (a, b = 0) => a - b;
const multiply = (a, b = 1) => a * b;
const divide = (a, b = 1) => b !== 0 ? a / b : "Cannot divide by zero";
function calculator(a, b, operation) {
return operation(a, b);
}
console.log(calculator(10, 5, add)); // 15
console.log(calculator(10, 5, divide)); // 2
JavaScript Strings
Strings in JavaScript are used to store and manipulate text. Strings are sequences of characters enclosed in quotes.
JavaScript provides many methods and properties to work with strings efficiently.
11.1 String Literals & Template Literals
String Literals:
let name = "Alice";
let greeting = 'Hello, ' + name + '!';
console.log(greeting);
Template Literals: Use backticks (\` \`
) and ${}
for expressions.
let name = "Alice";
let greeting = `Hello, ${name}!`;
console.log(greeting);
Task: Use template literals to create a message showing age and city dynamically.
11.2 Escape Characters
Escape characters allow special characters in strings.
let message = "Hello\nWorld"; // New line
let quote = "She said, \"Hello!\"";
console.log(message);
console.log(quote);
Task: Create a string that includes tabs, quotes, and a newline.
11.3 String Properties & Methods
Strings have several properties and methods:
let str = "JavaScript";
console.log(str.length); // 10
console.log(str.toUpperCase()); // JAVASCRIPT
console.log(str.toLowerCase()); // javascript
console.log(str.charAt(0)); // J
console.log(str.concat(" is fun")); // JavaScript is fun
console.log(str.slice(0, 4)); // Java
console.log(str.replace("Java", "Type")); // TypeScript
Task: Write a program that capitalizes the first letter of each word in a string.
11.4 Searching in Strings
let str = "Hello World";
console.log(str.indexOf("World")); // 6
console.log(str.includes("Hello")); // true
console.log(str.startsWith("Hell")); // true
console.log(str.endsWith("ld")); // true
console.log(str.search("World")); // 6
Task: Check if a string contains a specific word and its position.
11.5 String Conversion Methods
let num = 123;
let bool = true;
console.log(String(num)); // "123"
console.log(String(bool)); // "true"
console.log((456).toString()); // "456"
console.log(true.toString()); // "true"
Task: Convert numbers, booleans, and arrays into strings and concatenate them.
Mini Project: Simple Text Analyzer
Create a small program that takes a string input and shows:
- Total length of the string
- Number of words
- Uppercase version
- Lowercase version
- First character of each word capitalized
function textAnalyzer(text) {
console.log("Original Text: " + text);
console.log("Length: " + text.length);
console.log("Words: " + text.split(" ").length);
console.log("Uppercase: " + text.toUpperCase());
console.log("Lowercase: " + text.toLowerCase());
let capitalized = text.split(" ").map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
console.log("Capitalized: " + capitalized);
}
textAnalyzer("hello world, welcome to javascript!");
JavaScript Arrays
Arrays in JavaScript are used to store multiple values in a single variable. Arrays can hold elements of any type, including numbers, strings, objects, or even other arrays.
12.1 Single-Dimensional Arrays
Single-dimensional arrays are simple lists of values.
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits);
console.log(fruits[0]); // Access first element
Task: Create an array of 5 of your favorite movies and print the second movie.
12.2 Multi-Dimensional Arrays
Multi-dimensional arrays are arrays containing other arrays.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][1]); // 2
console.log(matrix[2][2]); // 9
Task: Create a 3x3 matrix and print the diagonal elements.
12.3 Array Methods
Commonly used array methods:
let colors = ["Red", "Green", "Blue"];
// Add elements
colors.push("Yellow"); // End
colors.unshift("Purple"); // Start
// Remove elements
colors.pop(); // End
colors.shift(); // Start
// Other methods
console.log(colors.includes("Green")); // true
console.log(colors.indexOf("Blue")); // 2
Task: Create an array of numbers, add two numbers to start and end, then remove one number from start and end.
12.4 Iteration Methods
Arrays can be iterated using loops and methods:
let numbers = [1, 2, 3, 4, 5];
// for loop
for(let i=0; i<numbers.length; i++) {
console.log(numbers[i]);
}
// for...of loop
for(let num of numbers) {
console.log(num);
}
// forEach
numbers.forEach(num => console.log(num));
Task: Iterate an array of student names and print a greeting for each.
12.5 Array Sorting
Arrays can be sorted and reversed:
let fruits = ["Banana", "Apple", "Mango"];
fruits.sort(); // Alphabetical
console.log(fruits);
let numbers = [3, 1, 4, 2, 5];
numbers.sort((a, b) => a - b); // Ascending
console.log(numbers);
numbers.reverse(); // Descending
console.log(numbers);
Task: Sort an array of ages in ascending and descending order.
Mini Project: Student Marks Analyzer
Create a program that:
- Stores marks of 5 students in an array
- Calculates the total and average marks
- Finds the highest and lowest marks
- Sorts the marks in ascending and descending order
let marks = [78, 92, 85, 66, 90];
// Total
let total = marks.reduce((sum, mark) => sum + mark, 0);
console.log("Total Marks: " + total);
// Average
console.log("Average Marks: " + total / marks.length);
// Highest & Lowest
console.log("Highest Marks: " + Math.max(...marks));
console.log("Lowest Marks: " + Math.min(...marks));
// Sort
console.log("Ascending: " + [...marks].sort((a,b) => a-b));
console.log("Descending: " + [...marks].sort((a,b) => b-a));
JavaScript Objects
Objects in JavaScript are collections of key-value pairs, where keys are strings (or symbols) and values can be of any type, including arrays or other objects.
13.1 Object Literals
Objects can be defined using curly braces {}
:
let person = {
name: "John",
age: 25,
city: "New York"
};
console.log(person);
console.log(person.name);
Task: Create an object for your favorite book with properties: title, author, and year.
13.2 Object Properties & Methods
Objects can have methods (functions as values):
let person = {
name: "Alice",
age: 30,
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // Hello, Alice
person.age = 31; // Modify property
console.log(person.age);
Task: Add a method to your book object to display its details.
13.3 Object Destructuring
Extract properties into variables easily:
let person = { name: "Bob", age: 28, city: "London" };
let { name, age } = person;
console.log(name); // Bob
console.log(age); // 28
Task: Destructure your book object and print the title and author.
13.4 Object Iteration (keys, values, entries)
You can loop through objects using Object.keys()
, Object.values()
, or Object.entries()
:
let person = { name: "Sam", age: 35, city: "Paris" };
// Keys
for(let key of Object.keys(person)) {
console.log(key);
}
// Values
for(let value of Object.values(person)) {
console.log(value);
}
// Entries
for(let [key, value] of Object.entries(person)) {
console.log(key + ": " + value);
}
Task: Loop through your book object and print key-value pairs.
13.5 Object.freeze(), Object.seal()
Object.freeze() prevents modifications to an object.
Object.seal() prevents adding/removing properties but allows modifying existing ones.
let person = { name: "Emma", age: 40 };
Object.freeze(person);
person.age = 41; // Not allowed
person.city = "Berlin"; // Not allowed
console.log(person);
let person2 = { name: "Liam", age: 29 };
Object.seal(person2);
person2.age = 30; // Allowed
person2.city = "Rome"; // Not allowed
console.log(person2);
Task: Freeze your book object and try to modify a property. Then seal it and try adding a new property.
13.6 Nested Objects
Objects can contain other objects:
let student = {
name: "John",
marks: {
math: 90,
science: 85
}
};
console.log(student.marks.math); // 90
console.log(student["marks"]["science"]); // 85
Task: Create a nested object for a course with properties: name, instructor, and syllabus (as another object with modules).
Mini Project: Employee Management
Create an employee object with the following requirements:
- Properties: name, id, department, salary
- A method to display employee details
- Nesting: Include a nested object for address with city, state, and zip
- Demonstrate modifying, freezing, and sealing the object
let employee = {
name: "Alice",
id: 101,
department: "IT",
salary: 50000,
address: { city: "New York", state: "NY", zip: 10001 },
display: function() {
console.log(`${this.name} (${this.id}) works in ${this.department}`);
}
};
employee.display();
employee.salary = 55000; // Modify
Object.freeze(employee);
// employee.department = "HR"; // Not allowed
console.log(employee);
JavaScript Built-in Objects
JavaScript provides several built-in objects that help in handling collections, performing mathematical operations, working with dates, and managing structured data like JSON.
14.1 Sets
Sets are collections of unique values:
let mySet = new Set([1, 2, 3, 3, 4]);
console.log(mySet); // Set { 1, 2, 3, 4 }
mySet.add(5);
mySet.delete(2);
console.log(mySet.has(3)); // true
console.log(mySet.size); // 4
Task: Create a set of favorite fruits and add/remove fruits.
14.2 Maps
Maps store key-value pairs where keys can be any type:
let myMap = new Map();
myMap.set("name", "Alice");
myMap.set("age", 25);
console.log(myMap.get("name")); // Alice
console.log(myMap.has("age")); // true
myMap.delete("age");
Task: Create a map of students and their scores, then retrieve a score.
14.3 WeakSet & WeakMap
WeakSet stores objects only and allows garbage collection:
let obj1 = { name: "John" };
let obj2 = { name: "Alice" };
let myWeakSet = new WeakSet([obj1]);
myWeakSet.add(obj2);
console.log(myWeakSet.has(obj1)); // true
WeakMap stores key-value pairs with object keys:
let wm = new WeakMap();
let keyObj = {};
wm.set(keyObj, "value");
console.log(wm.get(keyObj)); // value
Task: Use a WeakMap to store private data for objects.
14.4 Date Object & Methods
JavaScript provides Date
object to work with dates and times:
let now = new Date();
console.log(now);
let specificDate = new Date("2025-01-01");
console.log(specificDate.getFullYear()); // 2025
console.log(specificDate.getMonth()); // 0 (January)
console.log(specificDate.getDate()); // 1
Task: Display current date in DD/MM/YYYY format.
14.5 Math Object & Methods
The Math
object provides mathematical constants and functions:
console.log(Math.PI); // 3.141592653589793
console.log(Math.sqrt(16)); // 4
console.log(Math.floor(4.9)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.random()); // random number between 0 and 1
Task: Generate a random integer between 1 and 100 using Math.random()
.
14.6 JSON
JSON (JavaScript Object Notation) is used to store and exchange data:
let obj = { name: "Bob", age: 30 };
// Convert object to JSON string
let jsonString = JSON.stringify(obj);
console.log(jsonString); // {"name":"Bob","age":30}
// Convert JSON string back to object
let parsedObj = JSON.parse(jsonString);
console.log(parsedObj.name); // Bob
Task: Create a JSON string for a movie with title, director, and year, then parse it back to an object.
Mini Project: Student Records Management
Create a small student records system using built-in objects:
- Use a Set to store unique student IDs.
- Use a Map to map student IDs to their names.
- Store enrollment date using Date.
- Calculate age using Math methods.
- Serialize student data to JSON for storage.
JavaScript Events
In JavaScript, events are actions or occurrences that happen in the browser, such as clicking a button, moving the mouse, typing in a form, or loading a page. They allow developers to run code in response to user interactions or browser actions, making web pages interactive.
What is an Event?
An event is something that happens in the browser, triggered by:
- User actions: clicks, typing, scrolling, etc.
- Browser actions: page load, resize, or unload
- Programmatic triggers using JavaScript
Event Handlers
An event handler is a function executed when an event occurs. There are two main ways to define an event handler:
- Inline Event Handlers: Defined directly in HTML attributes.
- Event Listeners: Defined in JavaScript using
addEventListener()
. Recommended for better separation of HTML and JS.
The Event Object
When an event occurs, an event object is automatically passed to the handler. It contains information about the event, such as:
- Event type (
click
, keydown
, etc.)
- Target element (
event.target
)
- Mouse coordinates (
event.clientX
, event.clientY
)
- Keyboard key pressed (
event.key
)
15.1 Introduction to Events
Events can be triggered by user actions, browser actions, or programmatically using JavaScript.
document.getElementById("myBtn").onclick = function() {
alert("Button clicked!");
};
Task: Add a button to your page and display an alert when clicked.
15.2 Inline Events vs Event Listeners
Inline events are defined directly in HTML attributes, while event listeners are defined in JavaScript using addEventListener()
.
<button onclick="alert('Clicked!')">Click Me</button>
// Using Event Listener
document.getElementById("btn").addEventListener("click", function() {
alert("Clicked!");
});
Task: Convert an inline event to an event listener.
15.3 Mouse Events
Common mouse events include:
click
– when the mouse button is clicked
dblclick
– double click
mouseenter
/ mouseleave
– when mouse enters/leaves an element
mousemove
– when the mouse moves over an element
let box = document.getElementById("box");
box.addEventListener("mouseenter", function() {
box.style.backgroundColor = "yellow";
});
box.addEventListener("mouseleave", function() {
box.style.backgroundColor = "lightblue";
});
15.4 Keyboard Events
Keyboard events occur when the user presses a key:
keydown
– key pressed
keyup
– key released
keypress
– key pressed and held
document.addEventListener("keydown", function(event) {
console.log("Key pressed: " + event.key);
});
15.5 Form Events
Form events are triggered by user interaction with form elements:
submit
– when a form is submitted
change
– when input value changes
input
– as user types into an input field
let form = document.getElementById("myForm");
form.addEventListener("submit", function(e) {
e.preventDefault(); // prevent form submission
alert("Form submitted!");
});
15.6 Event Bubbling & Capturing
Event propagation occurs in two phases:
- Capturing Phase: Event moves from the root to the target element
- Bubbling Phase: Event bubbles up from the target element to the root
parentDiv.addEventListener("click", () => console.log("Parent clicked"), true); // capturing
childDiv.addEventListener("click", () => console.log("Child clicked")); // bubbling
15.7 Event Delegation
Event delegation is a technique where a parent element handles events for its child elements. It’s useful when child elements are created dynamically.
document.getElementById("list").addEventListener("click", function(e) {
if(e.target && e.target.nodeName == "LI") {
console.log("List item clicked: " + e.target.textContent);
}
});
Task: Create a dynamic list and handle clicks on list items using event delegation.
JavaScript DOM (Document Object Model)
The DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the page as a tree of nodes, allowing JavaScript to access, modify, and manipulate HTML elements, attributes, and content dynamically.
16.1 DOM Introduction
The DOM is a hierarchical tree structure where each element, attribute, and text node is a node object. Using JavaScript, you can interact with the DOM to create interactive and dynamic web pages.
16.2 Selecting Elements
You can select elements using different methods:
getElementById()
– select by ID
getElementsByClassName()
– select by class
getElementsByTagName()
– select by tag name
querySelector()
– select first matching CSS selector
querySelectorAll()
– select all matching CSS selectors
let header = document.getElementById("header");
let items = document.getElementsByClassName("item");
let firstBtn = document.querySelector(".btn");
let allBtns = document.querySelectorAll(".btn");
16.3 Modifying DOM Elements
Once selected, you can modify elements by changing their content or attributes.
let title = document.getElementById("title");
title.textContent = "New Title";
title.innerHTML = "<em>Updated Title</em>";
title.setAttribute("class", "highlight");
16.4 Adding & Removing Elements
You can create, insert, and remove elements dynamically:
let newDiv = document.createElement("div");
newDiv.textContent = "Hello World";
document.body.appendChild(newDiv); // add element
let oldDiv = document.getElementById("oldDiv");
oldDiv.remove(); // remove element
16.5 Styling Elements
You can change CSS styles directly via JavaScript:
let box = document.getElementById("box");
box.style.backgroundColor = "yellow";
box.style.fontSize = "20px";
box.style.border = "2px solid black";
16.6 DOM Navigation
DOM navigation allows you to move between parent, child, and sibling elements:
parentNode
– access parent element
children
– access child elements
firstElementChild
, lastElementChild
nextElementSibling
, previousElementSibling
let parent = element.parentNode;
let firstChild = element.firstElementChild;
let nextSibling = element.nextElementSibling;
16.7 DOM Forms & Input Handling
You can access and manipulate form input values using the DOM:
let form = document.getElementById("myForm");
let input = document.getElementById("username");
form.addEventListener("submit", function(e) {
e.preventDefault();
console.log("Username: " + input.value);
});
16.8 DOM Events & Event Listeners
DOM elements can listen for events using addEventListener()
. You can handle clicks, mouse movements, keyboard input, and more.
let btn = document.getElementById("btn");
btn.addEventListener("click", function() {
alert("Button clicked!");
});
16.9 DOM Collections & NodeLists
Methods like getElementsByClassName()
return HTMLCollections (live collections), whereas querySelectorAll()
returns NodeLists (static). You can iterate over NodeLists using forEach()
.
let items = document.querySelectorAll(".item");
items.forEach(item => {
item.style.color = "blue";
});
16.10 DOM Animations
You can animate elements using CSS transitions or JavaScript by updating properties over time.
let box = document.getElementById("box");
let pos = 0;
function moveBox() {
if(pos < 300) {
pos++;
box.style.left = pos + "px";
requestAnimationFrame(moveBox);
}
}
moveBox();
JavaScript BOM (Browser Object Model)
The BOM (Browser Object Model) allows JavaScript to interact with the browser window and its components outside the document.
It includes objects like window
, navigator
, screen
, location
, history
, and supports alerts, timers, and storage.
17.1 BOM Introduction
BOM provides the ability to manipulate the browser, handle windows, and control navigation.
It is different from the DOM, which deals with page content.
17.2 window Object
The window
object represents the browser window and is the global object in JavaScript.
Common properties and methods include:
window.innerWidth
, window.innerHeight
– viewport size
window.open(url, name, specs)
– open new window
window.close()
– close window
window.alert()
, window.confirm()
, window.prompt()
– dialogs
window.setTimeout(function, delay)
, window.setInterval(function, interval)
– timers
window.location
, window.navigator
, window.history
– access other BOM objects
// Example: Open new window and close after 3 seconds
let newWin = window.open("https://example.com", "_blank", "width=400,height=400");
setTimeout(() => newWin.close(), 3000);
17.3 document Object
The document
object belongs to the BOM via window.document
and allows full DOM access.
17.4 navigator Object
The navigator
object provides information about the browser:
// Browser info
console.log(navigator.userAgent);
console.log(navigator.platform);
console.log(navigator.language);
console.log(navigator.onLine);
17.5 screen Object
// Screen details
console.log(screen.width, screen.height);
console.log(screen.availWidth, screen.availHeight);
console.log(screen.colorDepth);
17.6 location Object
// Location properties
console.log(location.href);
console.log(location.protocol);
console.log(location.host);
console.log(location.pathname);
// Navigate to a new URL
// location.assign("https://example.com");
// Reload page
// location.reload();
17.7 history Object
// Navigate history
// history.back();
// history.forward();
// history.go(-2);
console.log(history.length);
17.8 Alerts, Prompts & Confirm
// Alerts
alert("Hello World");
// Confirm
let isOk = confirm("Do you want to proceed?");
console.log(isOk);
// Prompt
let name = prompt("Enter your name:");
console.log("Name:", name);
17.9 setTimeout() & setInterval()
// setTimeout executes once after delay
let timeoutId = setTimeout(() => console.log("Executed after 2 seconds"), 2000);
// setInterval executes repeatedly
let counter = 0;
let intervalId = setInterval(() => {
console.log("Count:", ++counter);
if(counter >= 5) clearInterval(intervalId);
}, 1000);
// Cancel timeout
// clearTimeout(timeoutId);
17.10 Cookies, LocalStorage, SessionStorage
// Cookies
document.cookie = "username=John; expires=Fri, 31 Dec 2025 12:00:00 GMT; path=/";
console.log(document.cookie);
// localStorage (persistent)
localStorage.setItem("name", "Alice");
console.log(localStorage.getItem("name"));
localStorage.removeItem("name");
localStorage.clear();
// sessionStorage (cleared on tab close)
sessionStorage.setItem("temp", "123");
console.log(sessionStorage.getItem("temp"));
sessionStorage.removeItem("temp");
sessionStorage.clear();
17.11 BOM vs DOM
DOM: Deals with document content (HTML elements, nodes).
BOM: Deals with browser environment (window, navigator, history, screen, location, storage, etc.).
Together, they allow full control over web pages and the browser environment.
Asynchronous JavaScript
Asynchronous JavaScript allows code to run without blocking the main thread. This is essential for handling operations like network requests, timers, or reading files while keeping the page responsive.
18.1 Synchronous vs Asynchronous Execution
Synchronous: Code runs line by line, blocking the next statement until the current one finishes.
Asynchronous: Code can start an operation and continue executing without waiting for it to finish.
// Synchronous
console.log("Start");
console.log("End");
// Asynchronous
console.log("Start");
setTimeout(() => console.log("Async Operation"), 2000);
console.log("End");
18.2 Callbacks
A callback is a function passed as an argument to another function to be executed later, usually after an asynchronous operation.
function fetchData(callback) {
setTimeout(() => {
callback("Data loaded");
}, 1000);
}
fetchData((data) => {
console.log(data);
});
18.3 Callback Hell
Nested callbacks can make code hard to read and maintain, a situation called callback hell:
doTask1((res1) => {
doTask2(res1, (res2) => {
doTask3(res2, (res3) => {
console.log("All tasks done", res3);
});
});
});
18.4 Promises
A Promise represents a future value and helps avoid callback hell.
It can be handled using .then()
for success and .catch()
for errors.
Multiple .then()
calls can also be chained together to perform sequential operations.
// Basic Promise example
let promise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if(success) resolve("Promise resolved");
else reject("Promise rejected");
}, 1000);
});
// Handling with then and catch
promise
.then((msg) => console.log(msg)) // If resolved
.catch((err) => console.log(err)); // If rejected
// Promise Chaining
promise
.then((msg) => {
console.log(msg);
return "Step 1 complete";
})
.then((nextMsg) => {
console.log(nextMsg);
return "Step 2 complete";
})
.then((finalMsg) => {
console.log(finalMsg);
})
.catch((err) => console.log("Error:", err));
18.5 Async & Await
async
functions return a Promise. await
pauses execution until the Promise resolves, making asynchronous code easier to read.
async function getData() {
try {
let data = await fetchDataAsync();
console.log(data);
} catch(err) {
console.log(err);
}
}
getData();
function fetchDataAsync() {
return new Promise((resolve) => {
setTimeout(() => resolve("Data loaded with async/await"), 1000);
});
}
18.6 setTimeout & setInterval
Timers are a simple form of asynchronous operations:
// Execute once after 2 seconds
let timeoutId = setTimeout(() => console.log("Executed after 2s"), 2000);
// Execute repeatedly every 1 second
let counter = 0;
let intervalId = setInterval(() => {
console.log("Counter:", ++counter);
if(counter >= 5) clearInterval(intervalId);
}, 1000);
18.7 Fetch API
The Fetch API allows making HTTP requests asynchronously. It returns a Promise that resolves to the response.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log("Error:", err));
// Using async/await
async function getPost() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log(data);
} catch(err) {
console.log("Error:", err);
}
}
getPost();
JavaScript Object-Oriented Programming (OOP)
JavaScript supports Object-Oriented Programming (OOP), which allows developers to structure code using objects, classes, and inheritance. OOP helps in creating modular, reusable, and maintainable code using concepts like encapsulation, polymorphism, abstraction, and inheritance.
19.1 Objects & Prototypes
Objects are collections of key-value pairs. In JavaScript, each object has a prototype from which it can inherit properties and methods.
// Object literal
let person = {
name: "Alice",
age: 25,
greet() {
console.log(Hello, I'm ${this.name});
}
};
person.greet(); // Hello, I'm Alice
// Constructor function with prototype
function Person(name, age) {
this.name = name;
this.age = age;
}
// Adding method to prototype
Person.prototype.sayHi = function() {
console.log(Hi, I'm ${this.name});
};
let p1 = new Person("Bob", 30);
p1.sayHi(); // Hi, I'm Bob
Explanation: Using prototypes, methods are shared across all instances rather than being recreated per object.
19.2 Constructor Functions
Constructor functions allow creating multiple objects of the same type with shared structure.
function Car(make, model) {
this.make = make;
this.model = model;
this.drive = function() {
console.log(${this.make} ${this.model} is driving);
};
}
let car1 = new Car("Toyota", "Corolla");
car1.drive(); // Toyota Corolla is driving
let car2 = new Car("Honda", "Civic");
car2.drive(); // Honda Civic is driving
Explanation: The this
keyword refers to the instance being created. Each instance has its own copy of properties and methods defined inside the constructor.
19.3 ES6 Classes
ES6 introduced class
syntax as a cleaner way to define constructor functions and prototypes.
class Animal {
constructor(name) {
this.name = name; // Instance property
}
speak() { // Method shared across instances
console.log(`${this.name} makes a sound`);
}
}
let dog = new Animal("Dog");
dog.speak(); // Dog makes a sound
Explanation: Classes are syntactic sugar over JavaScript prototypes, providing a clearer and more readable structure for OOP.
19.4 Class Inheritance
Classes can inherit properties and methods from another class using extends
. The super()
function is used to call the parent class constructor.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(${this.name} makes a sound);
}
}
// Dog inherits from Animal
class Dog extends Animal {
constructor(name, breed) {
super(name); // Calls parent constructor
this.breed = breed;
}
speak() {
console.log(${this.name} barks);
}
}
let dog = new Dog("Rex", "Labrador");
dog.speak(); // Rex barks
console.log(dog.breed); // Labrador
Explanation:
extends
allows the child class to inherit properties and methods from the parent class.
super()
calls the parent constructor so the inherited properties are initialized.
- Method overriding allows child classes to provide a new implementation of a parent method.
19.5 Encapsulation
Encapsulation hides internal data and only exposes necessary methods to access or modify it.
// Using private fields (#)
class BankAccount {
#balance = 0; // Private property
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
let account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
// console.log(account.#balance); // Error: private field
Explanation: Private fields (prefixed with #
) cannot be accessed from outside the class, ensuring data security.
19.6 Polymorphism
Polymorphism allows objects of different types to be treated the same way, often via method overriding.
class Animal {
speak() { console.log("Animal sound"); }
}
class Dog extends Animal {
speak() { console.log("Dog barks"); }
}
class Cat extends Animal {
speak() { console.log("Cat meows"); }
}
let animals = [new Dog(), new Cat()];
animals.forEach(a => a.speak());
// Dog barks
// Cat meows
Explanation: The same method name (speak
) behaves differently depending on the object type.
19.7 Abstraction
Abstraction hides internal implementation details and exposes only necessary functionality.
class Vehicle {
startEngine() {
console.log("Engine started");
}
move() {
console.log("Vehicle is moving");
}
}
let car = new Vehicle();
car.startEngine(); // Engine started
car.move(); // Vehicle is moving
// Internal engine logic is hidden
Explanation: Users interact with high-level methods without worrying about the internal logic.
19.8 Static Properties & Methods
Static members belong to the class itself rather than instances.
class Calculator {
static add(a, b) {
return a + b;
}
static PI = 3.1416;
}
console.log(Calculator.add(5, 3)); // 8
console.log(Calculator.PI); // 3.1416
// Cannot call static method on instance
let calc = new Calculator();
// calc.add(2,3); // Error
Explanation: Static members are useful for utility functions or constants that do not rely on instance properties.
JavaScript Modules
JavaScript modules are reusable pieces of code that help organize your application, avoid global namespace pollution, and manage dependencies. Modules allow you to export and import functions, objects, or primitives across different files.
20.1 Import & Export
The export
keyword allows you to make variables, functions, or classes available outside the module. The import
keyword lets you include those exported items in another file.
// utils.js
export const PI = 3.1416;
export function add(a, b) {
return a + b;
}
// default export
export default function subtract(a, b) {
return a - b;
}
// main.js
import subtract, { PI, add } from './utils.js';
console.log(PI); // 3.1416
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
20.2 Module Scope
Variables and functions declared inside a module are scoped to that module by default. They are not accessible globally unless explicitly exported.
// module.js
let privateVar = "I am private";
export let publicVar = "I am public";
// main.js
import { publicVar } from './module.js';
console.log(publicVar); // "I am public"
// console.log(privateVar); // Error: privateVar is not defined
20.3 CommonJS vs ES Modules
There are two module systems commonly used in JavaScript:
-
CommonJS (CJS) – Used in Node.js. Uses
require()
to import and module.exports
to export.
-
ES Modules (ESM) – Modern standard in both browser and Node.js. Uses
import
and export
.
// CommonJS example (Node.js)
// utils.js
const PI = 3.1416;
function add(a, b) { return a + b; }
module.exports = { PI, add };
// main.js
const { PI, add } = require('./utils.js');
console.log(PI); // 3.1416
console.log(add(2, 3)); // 5
ES Modules are recommended for modern JavaScript development because they support static analysis, tree shaking, and browser-native imports.
JavaScript Error Handling & Debugging
JavaScript provides tools for handling errors gracefully and debugging code effectively. Proper error handling ensures the application doesn’t crash and improves user experience. Debugging helps identify and fix problems in your code.
21.1 Types of Errors
Errors in JavaScript can be categorized into:
- Syntax Errors: Mistakes in code structure (e.g., missing brackets).
- Runtime Errors: Errors that occur during execution (e.g., accessing undefined variables).
- Logical Errors: Code runs but produces unexpected results (e.g., wrong calculation logic).
// Syntax Error
// console.log("Hello world" // missing closing parenthesis
// Runtime Error
console.log(x); // ReferenceError: x is not defined
// Logical Error
let result = 2 + 2;
console.log(result); // Expected 5, but output is 4
21.2 try...catch...finally
The try...catch
block allows you to catch errors and handle them without stopping program execution. The finally
block executes code regardless of whether an error occurred.
try {
let data = JSON.parse('invalid json');
console.log(data);
} catch (error) {
console.log("Error caught:", error.message);
} finally {
console.log("This block always executes");
}
21.3 Throwing Custom Errors
You can create and throw custom errors using the throw
statement to indicate specific issues in your code.
function checkAge(age) {
if(age < 18) {
throw new Error("Age must be 18 or older");
}
return "Access granted";
}
try {
console.log(checkAge(15));
} catch(e) {
console.log("Custom Error:", e.message);
}
21.4 Debugging with console methods
The console
object provides several methods to debug code:
console.log()
– Prints messages to the console.
console.error()
– Prints error messages.
console.warn()
– Prints warning messages.
console.table()
– Displays tabular data as a table.
console.trace()
– Shows the call stack trace.
console.log("Info message");
console.warn("Warning message");
console.error("Error message");
console.table([{name: "Alice", age: 25}, {name: "Bob", age: 30}]);
console.trace("Trace this function");
21.5 Using Browser DevTools
Modern browsers provide Developer Tools to debug JavaScript:
- Breakpoints: Pause execution at specific lines to inspect variables.
- Watch Expressions: Monitor values of variables in real-time.
- Call Stack: See the sequence of function calls.
- Network Tab: Debug AJAX and Fetch requests.
- Sources Tab: View and edit scripts, set breakpoints, and step through code.
Using DevTools and console methods together makes debugging easier and more effective.
JavaScript ES6+ Features
ES6 (ECMAScript 2015) and later versions introduced new features to make JavaScript more powerful, readable, and concise. These include new variable declarations, template literals, destructuring, arrow functions, iterators, generators, and more.
22.1 let, const, Template Literals
let and const are block-scoped variable declarations, unlike var
.
Template literals allow embedding expressions in strings using backticks ` `
.
let name = "Alice";
const age = 25;
console.log(`${name} is ${age} years old`); // Alice is 25 years old
22.2 Destructuring (Arrays & Objects)
Destructuring allows unpacking values from arrays or objects into distinct variables.
// Array destructuring
let [a, b] = [1, 2];
console.log(a, b); // 1 2
// Object destructuring
let person = {name: "Bob", age: 30};
let {name, age} = person;
console.log(name, age); // Bob 30
22.3 Rest & Spread Operators
The ...
syntax is used for both collecting multiple elements (rest) and expanding arrays/objects (spread).
// Rest
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Spread
let arr1 = [1, 2];
let arr2 = [...arr1, 3, 4];
console.log(arr2); // [1, 2, 3, 4]
22.4 Default Parameters
Functions can have default values for parameters if no argument is provided.
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
greet("Alice"); // Hello, Alice!
22.5 Arrow Functions
Arrow functions provide a concise syntax and lexically bind the this
value.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
const numbers = [1, 2, 3];
const squared = numbers.map(n => n * n);
console.log(squared); // [1, 4, 9]
22.6 Iterators & Generators
Iterators provide a standard way to traverse data structures. Generators are functions that can pause execution and yield multiple values over time.
// Iterator
let arr = [10, 20, 30];
let iterator = arr[Symbol.iterator]();
console.log(iterator.next().value); // 10
// Generator
function* genNumbers() {
yield 1;
yield 2;
yield 3;
}
let gen = genNumbers();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
22.7 Symbols
Symbols are unique and immutable data types often used as object property keys to avoid name collisions.
let sym1 = Symbol("id");
let sym2 = Symbol("id");
console.log(sym1 === sym2); // false
let obj = {};
obj[sym1] = 101;
console.log(obj[sym1]); // 101
22.8 Sets & Maps
Set: Collection of unique values.
Map: Key-value pairs with keys of any type.
// Set
let set = new Set([1, 2, 2, 3]);
console.log(set); // Set {1, 2, 3}
// Map
let map = new Map();
map.set("name", "Alice");
map.set("age", 25);
console.log(map.get("name")); // Alice
22.9 Promises, Async/Await
Promises represent asynchronous operations. async/await
syntax makes asynchronous code more readable.
// Promise
let promise = new Promise((resolve, reject) => setTimeout(() => resolve("Done"), 1000));
promise.then(msg => console.log(msg));
// Async/Await
async function fetchData() {
let result = await promise;
console.log(result);
}
fetchData();
22.10 Modules (import/export)
Modules allow splitting code into reusable files using export
and import
.
// export.js
export const name = "Alice";
export function greet() { console.log("Hello"); }
// import.js
import { name, greet } from './export.js';
console.log(name); // Alice
greet(); // Hello
Advanced JavaScript Topics
Advanced JavaScript topics enhance your understanding of the language and enable writing more robust, efficient, and maintainable code. This includes strict mode, hoisting, closures, scopes, higher-order functions, functional programming, graphics, and chart libraries.
23.1 Strict Mode
Strict mode is a way to enforce stricter parsing and error handling in your JavaScript code. It helps catch common coding mistakes and unsafe actions.
"use strict";
x = 10; // Error: x is not defined
function test() {
y = 20; // Error: y is not defined
}
test();
23.2 Hoisting
Hoisting is JavaScript's behavior of moving declarations to the top of their scope. Only declarations are hoisted, not initializations.
// var is hoisted
console.log(a); // undefined
var a = 5;
// let and const are not accessible before declaration
// console.log(b); // ReferenceError
let b = 10;
23.3 Closures
A closure is a function that has access to variables from its outer scope even after the outer function has executed.
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
}
}
let counter = outer();
counter(); // 1
counter(); // 2
23.4 Scopes
JavaScript has three main types of scope: global, function, and block scope.
// Global scope
let globalVar = "I am global";
function example() {
// Function scope
let localVar = "I am local";
if(true) {
// Block scope
let blockVar = "I am in a block";
console.log(blockVar);
}
// console.log(blockVar); // Error: blockVar is not defined
}
example();
23.5 Higher-Order Functions
A higher-order function is a function that takes another function as an argument, or returns a function.
function greet(name) {
return `Hello ${name}`;
}
function processUser(name, callback) {
console.log(callback(name));
}
processUser("Alice", greet); // Hello Alice
23.6 Functional Programming Concepts
JavaScript supports functional programming concepts such as immutability, pure functions, map, filter, and reduce.
// Pure function
function add(a, b) {
return a + b;
}
// Using map, filter, reduce
let numbers = [1, 2, 3, 4, 5];
let squared = numbers.map(n => n * n); // [1,4,9,16,25]
let evenNumbers = numbers.filter(n => n % 2 === 0); // [2,4]
let sum = numbers.reduce((acc, n) => acc + n, 0); // 15
23.7 JS Graphics & Animations
JavaScript can create graphics and animations using the Canvas API
, SVG
, or libraries like GSAP
.
// Canvas example
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);
23.8 Chart Libraries
JavaScript has many chart libraries like Chart.js
, D3.js
, and Highcharts
to create interactive and responsive charts. Charts can be of various types: bar, line, pie, radar, polar area, and more.
Chart.js Examples
// Bar Chart
const barData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple"],
datasets: [{
label: "Votes",
data: [12, 19, 3, 5, 2],
backgroundColor: [
"rgba(255, 99, 132, 0.7)",
"rgba(54, 162, 235, 0.7)",
"rgba(255, 206, 86, 0.7)",
"rgba(75, 192, 192, 0.7)",
"rgba(153, 102, 255, 0.7)"
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)"
],
borderWidth: 1
}]
};
const barConfig = { type: 'bar', data: barData, options: { responsive: true } };
const barChart = new Chart(document.getElementById('barChart'), barConfig);
// Line Chart
const lineData = {
labels: ["Jan", "Feb", "Mar", "Apr", "May"],
datasets: [{
label: "Revenue",
data: [1500, 2000, 1800, 2200, 2400],
fill: false,
borderColor: "rgba(75, 192, 192, 1)",
tension: 0.1
}]
};
const lineConfig = { type: 'line', data: lineData, options: { responsive: true } };
const lineChart = new Chart(document.getElementById('lineChart'), lineConfig);
// Pie Chart
const pieData = {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
label: "Population",
data: [300, 150, 100],
backgroundColor: ["red", "blue", "yellow"]
}]
};
const pieConfig = { type: 'pie', data: pieData, options: { responsive: true } };
const pieChart = new Chart(document.getElementById('pieChart'), pieConfig);
D3.js Example (Advanced Visualization)
D3.js is a powerful library for creating dynamic, interactive data visualizations. It provides full control over SVG elements.
// Example: Simple Bar Chart with D3.js
const data = [10, 15, 20, 25, 30];
const width = 500;
const height = 200;
const svg = d3.select("#d3Chart")
.append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", (d, i) => i * 60)
.attr("y", d => height - d * 5)
.attr("width", 50)
.attr("height", d => d * 5)
.attr("fill", "teal");
With Chart.js you can easily create responsive charts with minimal code, while D3.js is better for highly customized, interactive, and complex visualizations.
24. JS Practice Tasks & Mini Projects
Practice is the best way to learn JavaScript. Below are categorized tasks and mini projects
based on different topics of JavaScript (variables, arrays, DOM, async, events, graphics, and games).
Each section contains practical exercises and small project ideas.
24.1 Variables & Data Types Task
Tasks:
- Create variables using
var
, let
, const
.
- Check the data type of variables using
typeof
.
- Convert string to number and vice versa.
Mini Project: Build a simple student info form and display values with their data types.
24.2 Operators & Expressions Practice
- Write programs to calculate area of rectangle, circle, triangle.
- Practice arithmetic, comparison, and logical operators.
Mini Project: Create a simple calculator.
24.3 Conditional Statements Task
- Check if a number is even or odd.
- Grade calculation based on marks.
Mini Project: Build a login check system (username/password).
24.4 Single & Multi-Dimensional Array Tasks
- Store 5 numbers in an array and find the max/min.
- Work with 2D arrays (matrix addition).
24.5 Array Methods Practice
- Use
map()
, filter()
, reduce()
.
- Find duplicate elements in an array.
Mini Project: Shopping cart total calculation.
24.6 Sorting & Iteration Mini Projects
- Sort an array of student names alphabetically.
- Sort numbers in ascending/descending order.
Mini Project: Leaderboard sorting system.
24.7 String Methods & Searching Tasks
- Find substring using
indexOf()
& includes()
.
- Change case using
toUpperCase()
, toLowerCase()
.
24.8 String Conversion & Manipulation Project
Mini Project: Build a word counter tool (count words, characters, spaces).
24.9 Object Literals & Property Access Tasks
- Create an object
person
with properties name, age, city.
- Access and update values using dot and bracket notation.
24.10 Object Destructuring & Iteration Practice
- Use destructuring on objects and arrays.
- Loop through object keys/values using
for...in
and Object.keys()
.
24.11 DOM Selection & Manipulation Tasks
- Select elements by ID, class, tag.
- Change text, style, and attributes dynamically.
24.12 DOM Forms & Input Handling Project
Mini Project: Create a form validation system (check empty fields, email format, password length).
24.13 DOM Events & Event Listeners Practice
- Click event to change background color.
- Keypress event to display typed keys.
24.14 DOM Animations Mini Project
Mini Project: Create an image slider with next/prev buttons.
24.15 Mouse, Keyboard, Form Event Tasks
- Mouseover effect on images.
- Keyboard shortcuts using
keydown
.
24.16 Event Bubbling & Delegation Practice
Mini Project: Build a dynamic to-do list (add/remove tasks with event delegation).
24.17 Fetch API
- Fetch data from a public API (e.g., JSONPlaceholder).
- Display results on webpage.
24.18 Promises & Async/Await Task
Mini Project: Create a weather app using Fetch + Async/Await.
24.19 Canvas Basics & Shapes Task
- Draw rectangles, circles, and lines using
<canvas>
.
24.20 Canvas Animations Project
Mini Project: Create a bouncing ball animation.
24.21 Chart.js Bar, Line, Pie Chart Task
Use Chart.js to create basic bar, line, and pie charts.
24.22 Interactive Chart Mini Project
Mini Project: Create a sales dashboard with dynamic charts.
24.23 Tic Tac Toe Game
Mini Project: Build a 2-player Tic Tac Toe game with DOM manipulation.
24.24 Stone-Paper-Scissors Game
Mini Project: Create a Rock-Paper-Scissors game with random computer moves.