What is JavaScript?
JavaScript is a high-level, interpreted programming language that enables dynamic
behavior on websites.
Compiled Languages:
In compiled languages, the entire source code is converted into machine code by a
compiler before the program is run. This compiled code can then be executed
directly by the computer.
Interpreted Languages:
In contrast, interpreted languages use an interpreter, which reads and executes the
source code line by line. The interpreter translates each line into machine-
executable instructions at runtime.
It is a core technology of the web, alongside HTML and CSS.
HTML - structures the content
CSS - styles the content
JavaScript - makes it interactive
Key Features of JavaScript
Client-side scripting: Runs in the user's browser without needing server interaction
Object-oriented and event-driven
In JavaScript, almost everything is an object — strings, arrays, functions, and user-
defined entities.
Encapsulation: You can group related data and functions together into objects.
class Car
{
Car (brand)
{
this.brand = brand;
}
drive()
{
console.log(`${this.brand} is driving`);
}
}
const myCar = new Car("Toyota");
myCar.drive(); // Output: Toyota is driving
JavaScript supports key OO principles like:
Encapsulation
Abstraction
Inheritance
Polymorphism
Event-Driven
JavaScript is event-driven because:
It reacts to user interactions or system events like clicks, form submissions, key
presses, timers, etc.
Event handlers or callback functions are attached to events and executed when those
events occur.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
document. getElementById("btn").onclick = function()
alert("Button clicked!");
};
Cross-platform compatibility
JavaScript code can run across different platforms and devices without
modification.
Write JavaScript once, and it will work on:
All major browsers (Chrome, Firefox, Safari, Edge, etc.)
Different operating systems (Windows, macOS, Linux, Android, iOS)
Various devices (desktops, laptops, tablets, smartphones)
1.Variables
Used to store data values.
let name = "John";
const age = 25;
2. Data Types
String: "Hello"
Number: 100
Boolean: true or false
Object, Array, Null, Undefined
3. Operators
Arithmetic: +, -, *, /
Comparison: ==, ===, >, <
Logical: &&, ||, !
4. Functions
In JavaScript, a function is a block of code designed to perform a specific
task.
You can define it once and reuse it multiple times.
Functions allow you to organize your code into reusable pieces, making it
more readable, manageable, and efficient.
Why use functions?
Reusability: Write once, use many times.
Modularity: Break your program into smaller, manageable parts.
Maintainability: Easier to test and update.
Syntax:
function functionName (parameters ) // Arguments
// code to execute
return result; // (optional)
Ex 1:Reusable blocks of code.
function greet(name)
return "Hello " + name;
}
Ex 2:
// Function to add two numbers
function addNumbers(a, b)
return a + b;
// Calling the function
let number1 = 5;
let number2 = 10;
let result = addNumbers (number1, number2);
// Display the result
console.log("The sum is: " + result);
Explanation:
function addNumbers(a, b) defines a function that takes two parameters.
return a + b; returns the sum of the two numbers.
We call the function with addNumbers(number1, number2) and store the
result.
console.log() prints the result to the console.
Types of Functions in JavaScript:
1. Named functions
function sayHello() {
console.log("Hello!");
}
2. Anonymous functions (often used with variables)
const greet = function()
console.log("Hi!");
};
5. Control Structures
if / else for conditional execution
for, while loops for iteration
if (age > 18)
console.log("Adult");
Example 1: Check if a number is positive or negative
let number = 10;
if (number >= 0)
console.log("The number is positive.");
else
{
console.log("The number is negative.");
Example 2: Check if a person is eligible to vote
let age = 20;
if (age >= 18) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}
Example 3: Find the largest of two numbers
let a = 15;
let b = 25;
if (a > b) {
console.log("a is greater than b.");
} else if (a < b) {
console.log("b is greater than a.");
} else {
console.log("Both numbers are equal.");
}
Example 4: Grade based on marks
let marks = 82;
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("Grade: F");
}
Example 5: Check if a number is even or odd
let num = 7;
if (num % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
Example 6: Print numbers from 1 to 5
for (let i = 1; i <= 5; i++)
{
console.log(i);
}
Example 7: Print even numbers between 1 and 10
for (let i = 1; i <= 10; i++)
{
if (i % 2 === 0) {
console.log(i);
}
}
Example 8: Sum of first 10 natural numbers
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
}
console.log("Sum:", sum);
Example 9: Print numbers from 1 to 5
let i = 1;
while (i <= 5)
{
console.log(i);
i++;
}
Example 10: Print odd numbers from 1 to 10
let i = 1;
while (i <= 10) {
if (i % 2 !== 0) {
console.log(i);
}
i++;
}
Example 11: Factorial of a number
let num = 5;
let fact = 1;
let i = 1;
while (i <= num) {
fact *= i;
i++;
}
console.log("Factorial of", num, "is", fact);
6. Events
JavaScript can respond to user actions like clicks, keystrokes, etc.
document. getElementById("btn").onclick = function()
alert("Button clicked!");
};
1.Example: Button Click Event
<!DOCTYPE html>
<html>
<head>
<title>Event Example</title>
</head>
<body>
<h2>Click the Button</h2>
<!-- Button -->
<button onclick="showMessage()">Click Me</button>
<!-- Area to display the message -->
<p id="output"></p>
<!-- JavaScript Function -->
<script>
function showMessage() {
document.getElementById("output").innerText = "You clicked the button!";
</script>
</body>
</html>
Explanation :
When the user clicks the button, the function showMessage() is triggered.
The function changes the text inside the <p> element with ID output.
2.Mouse Over Event (onmouseover)
<!DOCTYPE html>
<html>
<body>
<h3 onmouseover="changeColor(this)">Hover over me!</h3>
<script>
function changeColor(element)
{
element.style.color = "red";
}
</script>
</body>
</html>
3.Key Press Event (onkeydown)
<!DOCTYPE html>
<html>
<body>
<input type="text" onkeydown="detectKey(event)" placeholder="Type something">
<p id="keyOutput"></p>
<script>
function detectKey(e) {
document.getElementById("keyOutput").innerText = "You pressed: " + e.key;
}
</script>
</body>
</html>
4.Page Load Event (onload)
<!DOCTYPE html>
<html onload="welcome()">
<body>
<script>
function welcome() {
alert("Welcome to the page!");
}
// Better approach: attach onload via JS
window.onload = function() {
alert("Welcome to the page!");
};
</script>
</body>
</html>
5. Form Submit Event
<!DOCTYPE html>
<html>
<body>
<form onsubmit="return validateForm()">
<label>Enter your name:</label>
<input type="text" id="name">
<button type="submit">Submit</button>
</form>
<script>
function validateForm() {
var name = document.getElementById("name").value;
if (name === "") {
alert("Name must be filled out");
return false; // prevent form from submitting
}
alert("Form submitted!");
return true;
}
</script>
</body>
</html>
Object:
Concept of Objects in JavaScript
In JavaScript, an object is a collection of key-value pairs used to store and organize data.
It's one of the most important and flexible data types in JavaScript.
Object Syntax:
const objectName =
{
key1: value1,
key2: value2,
key3: function() { // method
}
};
Example:
const person =
{
name: "sathia",
age: 50,
greet: function() {
console.log("Hello, I'm " + this.name);
}
};
console.log(person.name); // Access property
person.greet(); // Call method
Ways to Create Objects
Object Literal (Most Common):
const car = { brand: "Toyota", model: "Camry" };
Using new Object():
const car = new Object();
car.brand = "Toyota";
Constructor Function:
function Person(name, age)
{
this.name = name;
this.age = age;
}
const p1 = new Person("John", 30);
1. Basic Object Creation and Access
Defines a person object and logs the values of its properties.
<!DOCTYPE html>
<html>
<body>
<script>
// Define an object
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
// Access and display properties
console.log("Name: " + person.firstName + " " + person.lastName);
console.log("Age: " + person.age);
</script>
</body>
</html>
2. Object with Method
Creates a car object with a method start() that prints a message.
<!DOCTYPE html>
<html>
<body>
<script>
const car = {
brand: "Toyota",
model: "Camry",
start: function() {
console.log("The car has started!");
}
}
car.start(); // Calling method
</script>
</body>
</html>
3. Using this Keyword
Demonstrates the use of this to refer to the object’s own properties.
<!DOCTYPE html>
<html>
<body>
<script>
const student = {
name: "Moorthy",
course: "Comuter Science",
details: function() {
return this.name + " is studying " + this.course;
}
};
console.log(student.details());
</script>
</body>
</html>
4. Nested Objects
<!DOCTYPE html>
<html>
<body>
<script>
const employee = {
name: "BALU",
department: {
name: "ADS",
location: "Ground Floor"
}
};
console.log("Name: " + employee.name);
console.log("Department: " + employee.department.name);
console.log("Location: " + employee.department.location);
</script>
</body>
</html>
Object Constructor Function
<!DOCTYPE html>
<html>
<body>
<script>
function Book(title, author)
{
this.title = title;
this.author = author;
}
const myBook = new Book("C++", "E.Balagurusamy");
console.log(myBook.title + " by " + myBook.author);
</script>
</body>
</html>
Nested Objects
const employee = {
name: "Bob",
address: {
city: "Chennai",
pin: "600001"
}
};
console.log(employee.address.city); // Chennai
Looping Through Objects
for (let key in person)
{
console.log(key + ": " + person[key]);
}
Array:
The concept of arrays in JavaScript is fundamental for handling and storing multiple values in a single
variable.
Concept of Array
An array in JavaScript is a data structure that holds an ordered list of values.
These values (called elements) can be of any type: numbers, strings, objects, other arrays, etc.
Declaring an Array
Using Square Brackets (Recommended):
let fruits = ["apple", "banana", "cherry"];
Accessing Array Elements
Array indices start from 0.
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"
Using the Array Constructor:
let numbers = new Array(1, 2, 3, 4);
Common Array Methods
Method Description
push() Adds element to the end
pop() Removes element from the end
shift() Removes element from the beginning
unshift() Adds element to the beginning
length Returns number of elements
splice() Adds/removes elements at specific index
slice() Extracts a section of the array
indexOf() Returns index of a specific element
includes() Checks if an element exists
forEach() Iterates over array
map() Creates a new array by applying a function
filter() Filters elements based on condition
let numbers = [1, 2, 3, 4, 5];
numbers.push(6); // [1, 2, 3, 4, 5, 6]
numbers.pop(); // [1, 2, 3, 4, 5]
let even = numbers.filter(n => n % 2 === 0); // [2, 4] // filter the element based on condition
Types of Arrays
Numeric Array – Stores numbers.
String Array – Stores strings.
Mixed Array – Can store different data types.
1. Basic Numeric Array
let marks = [85, 90, 78, 92, 88];
console.log(marks); // Output: [85, 90, 78, 92, 88]
2. Accessing Elements
console.log(marks[0]); // 85
console.log(marks[3]); // 92
3. Adding Numbers to an Array
marks.push(95); // Adds 95 to the end
marks.unshift(80); // Adds 80 to the beginning
console.log(marks); // [80, 85, 90, 78, 92, 88, 95]
4. Removing Numbers from an Array
marks.pop(); // Removes last number (95)
marks.shift(); // Removes first number (80)
console.log(marks); // [85, 90, 78, 92, 88]
5. Looping Through a Numeric Array
for (let i = 0; i < marks.length; i++)
{
console.log(`Student ${i + 1}: ${marks[i]}`);
}
6. Using forEach() Method
marks.forEach(function(mark)
{
console.log(mark * 2); // applying function to Multiply each mark by 2
});
7. Using map() to Create a New Array
let bonusMarks = marks.map(mark => mark + 5); // applying function to create new array
console.log(bonusMarks); // [90, 95, 83, 97, 93]
8. Filtering Even Numbers
let evenMarks = marks.filter(mark => mark % 2 === 0); // Filters elements based on
condition
console.log(evenMarks); // [90, 78, 92, 88]
9. Finding the Sum of All Numbers
let sum = marks.reduce((total, mark) => total + mark, 0);
console.log("Total Marks:", sum); // Total Marks: 433
10. Sorting a Numeric Array
let sortedMarks = marks.sort((a, b) => a - b); // Ascending order
console.log(sortedMarks); // [78, 85, 88, 90, 92]
Build in Object:
Math Object
console.log(Math.PI); // 3.141592653589793
console.log(Math.round(4.6)); // 5
console.log(Math.floor(4.9)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.pow(2, 3)); // 8
console.log(Math.sqrt(16)); // 4
console.log(Math.max(10, 20, 5)); // 20
console.log(Math.min(10, 20, 5)); // 5
console.log(Math.random()); // Random number between 0 and 1
Date Object
Used for working with dates and times.
let now = new Date();
console.log(now); // Current date and time
console.log(now.getFullYear()); // e.g. 2025
console.log(now.getMonth()); // Month (0–11)
console.log(now.getDate()); // Day of the month (1–31)
console.log(now.getDay()); // Day of the week (0–6)
console.log(now.getHours()); // Current hour
console.log(now.toDateString()); // e.g. "Sat Jun 28 2025"
String Object
let message = "Hello JavaScript";
console.log(message.length); // 16
console.log(message.toUpperCase()); // "HELLO JAVASCRIPT"
console.log(message.toLowerCase()); // "hello javascript"
console.log(message.indexOf("Java")); // 6
console.log(message.slice(6, 10)); // "Java"
console.log(message.replace("JavaScript", "World")); // "Hello World"
Number Object
Used for numeric conversions.
let num = 123.456;
console.log(num.toFixed(2)); // "123.46"
console.log(num.toString()); // "123.456"
console.log(Number("123")); // 123
console.log(Number("123abc")); // NaN
Boolean Object
Used to represent logical values
let x = Boolean(10 > 5);
console.log(x); // true
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hi")); // true
Array Object
Already covered earlier, here's a quick reminder:
let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
console.log(arr.includes(2)); // true
Object Object
let student = {
name: "Rahul",
age: 21,
course: "B.Tech"
};
console.log(student.name); // Rahul
console.log(Object.keys(student)); // ["name", "age", "course"]
console.log(Object.values(student)); // ["Rahul", 21, "B.Tech"]
RegExp (Regular Expression) Object
Used for pattern matching.
let text = "The rain in Spain stays mainly in the plain";
let result = text.match(/ain/g);
console.log(result); // ["ain", "ain", "ain", "ain"]
Javascript Debuggers
Programming code might contain syntax errors, or logical errors.
Many of these errors are difficult to diagnose.
Searching for (and fixing) errors in programming code is called code debugging.
Forcing errors to be reported to the user, Built-in debuggers can be turned on
Activate debugging in your browser (Chrome, IE, Firefox) with F12, and select
"Console" in the debugger menu.
JavaScript debuggers and debugging tools that can help developers inspect,
Track, and fix issues in their JavaScript code :
The console.log() Method
If your browser supports debugging, you can use console.log() to display JavaScript values in the
debugger window:
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>Activate debugging in your browser (Chrome, IE, Firefox) with F12, and
select "Console" in the debugger menu.</p>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
Setting Breakpoints
In the debugger window, you can set breakpoints in the JavaScript code.
At each breakpoint, JavaScript will stop executing, and let you examine
JavaScript values.
After examining values, you can resume the execution of code (usea play
button).
The debugger Keyword
The debugger keyword stops the execution of JavaScript, and calls (if
available) the debugging function.
This has the same function as setting a breakpoint in the debugger.
If no debugging is available, the debugger statement has no effect.
With the debugger turned on, this code will stop executing before it executes
the third line.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Debugger</h2>
<p id="demo"></p>
<p>With the debugger turned on, the code below should stop executing before it executes the
third line.</p>
<script>
let x = 15 * 5;
debugger;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Browsers' Debugging Tools
Chrome
Open the browser.
From the menu, select "More tools".
From tools, choose "Developer tools".
Finally, select Console.
Firefox
Open the browser.
From the menu, select "Web Developer".
Finally, select "Web Console".
Edge
Open the browser.
From the menu, select "Developer Tools".
Finally, select "Console".
Opera
Open the browser.
From the menu, select "Developer".
From "Developer", select "Developer tools".
Finally, select "Console".
Document Object Model (DOM)
The Document Object Model (DOM) is a programming interface for web documents.
Programming interface: a set of rules and specifications that allows different software
systems to communicate and interact with each other
It represents the structure of an HTML or XML document as a tree of objects that can be
accessed, modified, and manipulated using programming languages like JavaScript.
Basic Concept of DOM
1. Tree Structure:
o The DOM organizes an HTML document as a hierarchical tree of nodes.
o Each part of the document (tags, attributes, text) is a node in this tree.
Example:
<html>
<body>
<h1>Hello</h1>
<p>World</p>
</body>
</html>
DOM Tree:
Document
└── html
└── body
├── h1 → "Hello" // Elements of the node
└── p → "World"
Node Types:
Element node → HTML tags like <div>, <p>, etc.
Text node → Actual text inside elements.
Attribute node → Properties like id, class, etc.
Document node → The root of the DOM tree.
Accessing the DOM (via JavaScript):
JavaScript can interact with the DOM using the document object.
JS CODE:
document.getElementById("myId");
document.querySelector("p"); // to select a group of elements in the Document Object Model (DOM) based on a CSS
selector
document.createElement("div");
Example: sample code of HTML + JavaScript code that shows how to access and manipulate the DOM:
<!DOCTYPE html>
<html>
<head>
<title>DOM Access Example</title>
</head>
<body>
<h1 id="main-title">Welcome!</h1>
<p class="info">This is a sample paragraph.</p>
<button onclick="changeContent()">Click Me</button>
<script>
// Accessing an element by ID
const title = document.getElementById("main-title");
// Accessing an element by class name
const paragraph = document.querySelector(".info");
// Accessing all elements by tag name
const allParagraphs = document.getElementsByTagName("p");
// Function to modify DOM content
function changeContent()
{
title.textContent = "Title Changed!";
paragraph.style.color = "blue";
paragraph.textContent = "The content has been updated.";
}
</script>
</body>
</html>
Explanation:
document.getElementById("main-title"): accesses the <h1> element.
document.querySelector(".info"): selects the first element with class info.
document.getElementsByTagName("p"): gets all <p> elements as a collection.
textContent and style are used to change the content and appearance.
Modifying the DOM:
You can change content, style, or structure of the page dynamically.
JS
const para = document.querySelector("p");
para.textContent = "New text content!";
para.style.color = "blue";
Events and Interactivity:
DOM allows adding event listeners to elements.
JS:
button.addEventListener("click", function() )
{
alert("Button clicked!");
});
Example: Sample Code: Events and Interactivity
<!DOCTYPE html>
<html>
<head>
<title>DOM Events Example</title>
</head>
<body>
<h2 id="greeting">Hello, Visitor!</h2>
<button id="changeBtn">Change Text</button>
<button id="colorBtn">Change Color</button>
<script>
// Access DOM elements
const greeting = document.getElementById("greeting");
const changeBtn = document.getElementById("changeBtn");
const colorBtn = document.getElementById("colorBtn");
// Add event listeners
changeBtn.addEventListener("click", function() {
greeting.textContent = "Welcome to JavaScript Events!";
});
colorBtn.addEventListener("click", function() {
greeting.style.color = "green";
});
</script>
</body>
</html>
Code Explanation:
This Code Does:
When you click "Change Text", the heading (<h2>) text is updated.
When you click "Change Color", the heading text turns green.
addEventListener("click", ...) is used to bind interactive
behavior to buttons.
Basic Concept of DOM: The Document Tree
The Document Object Model (DOM) represents an HTML or XML document as a tree
structure, where each element, attribute, and piece of text is a node connected in a
hierarchical parent-child relationship.
What is the Document Tree?
The document tree is a tree-like representation of an HTML page.
The root node is the document, and it contains all other nodes as children.
This structure allows JavaScript to easily navigate, modify, and interact with the web
page content.
Node Types in the Tree:
Node Type Example Description
Document document The root of the DOM tree
Element Node <html>, <body>, <p> HTML tags
Text Node "Hello" Text inside elements
Attribute Node id="main" Element attributes
Comment Node <!-- a comment --> Comments in the HTML
Visual Example:
HTML:
<html>
<body>
<h1>Hello</h1>
<p>World</p>
</body>
</html>
DOM Tree:
CSS:
Document
└── html
└── body
├── h1
│ └── "Hello"
└── p
└── "World"
Explanation:
html is a child of document.
body is a child of html.
h1 and p are children of body.
"Hello" and "World" are text nodes inside h1 and p.
Why the Document Tree Matters
It enables JavaScript to:
Traverse: parentNode, childNodes, nextSibling
Access: getElementById, querySelector
Modify: textContent, setAttribute, innerHTML
Listen to events: addEventListener