JavaScript
Introduction
JavaScript is a client-side scripting language
Used to make web pages interactive
Developed by Brendan Eich in 1995
Supported by all modern browsers (Chrome, Firefox, Edge,
etc.)
“JavaScript is an object-based, client-side scripting language
that you can use to make Web pages more dynamic.”
JavaScript works with:
HTML → Structure (what appears on the page)
CSS → Design (colors, layout, fonts)
JavaScript → Behavior (actions and logic)
Why JavaScript is Needed?
HTML alone creates only static pages (no action).
JavaScript makes pages dynamic.
Examples:
Checking login form details
Showing pop-up messages
Changing content without reloading the page
Advantages of JavaScript
1. Speed
Runs directly in the browser.
No need to contact the server every time.
2. Reduces Server Load
Most work is done on the user’s computer.
3. Easy to Learn
Simple syntax.
Good for beginners.
4. Rich User Interface
Used for sliders, animations, drag-and-drop features.
Limitations of JavaScript
Security issues (client-side code visible)
Browser compatibility issues
Not suitable for complex applications alone
JavaScript is great, but it works best with other technologies.
General working of JavaScript:
Writing a “Hello World” Script:
This is the first basic program in any language.
Example:
alert("Hello World");
OR
[Link](“Hello World”);
JavaScript Comments
Used to explain code
Single-line comment
// This is a comment
Multi-line comment
/* This is
a multi-line comment */
JavaScript Syntax
Syntax means rules to write code.
JavaScript is case-sensitive (Name ≠ name)
Statements usually end with ;
Example:
var x = 10;
var y = 20;
Variables in JavaScript
Variables store data values.
Keywords:
var → old method
let → recommended
const → fixed value
Example:
let name = “Anamika";
var age = 20;
const pi = 3.14;
Output in JavaScript
Ways to display output:
alert() → Pop-up message
alert("Welcome to JavaScript");
[Link]() → Shows output on webpage
[Link]("Hello Students");
[Link]() → Shows output in browser console
[Link]("JavaScript Output");
JavaScript in HTML
JavaScript can be written inside <script> tag
Example:
<script>
alert("Hello BCA Students");
</script>
The browser understands that code inside <script> is JavaScript.
Javascript Arrays
An Array is an object type designed for storing data collections.
Key characteristics of JavaScript arrays are:
❑ Elements: An array is a list of values, known as elements.
❑ Ordered: Array elements are ordered based on their index.
❑ Zero indexed: The first element is at index 0, the second at index 1, and so
on.
❑ Dynamic size: Arrays can grow or shrink as elements are added or
removed.
❑ Heterogeneous: Arrays can store elements of different data types
(numbers, strings, objects and other arrays).
Creating an Array
The most common and recommended way to create an array is using the
array literal syntax [].
// An array of strings
let fruits = ["Apple", "Orange", "Plum"];
// An array with mixed data types
let mixedData = ["String", null, 7, [1, 2]];
// An empty array
let emptyArray = [];
Using the JavaScript Keyword new
Example
const cars = new Array( "Volvo", "BMW");
Operators in Javascript
Operators perform operations by taking one or more values, to give another value.
The following are the operators in JavaScript:
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Conditional Operators
Bitwise operators
Special operators
Arithmetic Operators
Example:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arithmetic Operator</h1>
<p id="test"></p>
<script>
let a = 10;
let b = 20
let res = a + b
[Link]("test").innerHTML = "Sum = "+res;
</script>
</body>
</html>
Assignment Operator
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Assignment Operator</h1>
<p id="test"></p>
<script>
let a = 20;
a += 50;
[Link]("test").innerHTML = "Sum = "+a;
</script>
</body>
</html>
Comparison Operators
Logical Operators
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Logical Operator</h1>
<p id="test"></p>
<script>
let a = true;
let b = false;
[Link]("test").innerHTML = (a&&b)
</script>
</body>
</html>
Conditional Operator
Conditional operator evaluates Boolean expressions, with three operands.
It is also known as the ternary operator.
Syntax:
variable_name = (expression) ? value1 ( if true) : value2 (if false)
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Conditional Operator</h1>
<p id="test"></p>
<script>
let marks = 90;
res = (marks > 50) ? "Student Passed" : "Student Failed";
[Link]("test").innerHTML = res;
</script>
</body>
</html>
JavaScript Bitwise Operators
Bitwise operators treat its operands as a set of 32-bit binary digits (zeros and
ones) and perform actions. However, the result is shown as a decimal value.
Special Operators
Special Operators in JavaScript
Conditional (Ternary) Operator (?:)
Short form of if...else
Example:
let result = (age >= 18) ? "Adult" : "Minor";
Comma Operator (,)
Evaluates multiple expressions and returns the last one.
Example:
let x = (1, 2, 3); // x = 3
delete
Deletes object properties.
Example:
delete [Link];
Precedence
JavaScript Data Types
Type Description
Number A number representing a numeric value
Bigint A number representing a large integer
String A text of characters enclosed in quotes
Boolean A data type representing true or false
Undefined A variable with no assigned value
Null A value representing object absence
Symbol A unique primitive identifier
Object A collection of key-value pairs of data
The typeof Operator
Use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator returns the type of a variable or an expression:
Example:
typeof “" // Returns "string“
typeof 0 // Returns "number“
typeof 3.14 // Returns "number“
const fruits = ["apples", "bananas", "oranges"];
[Link](typeof fruits);
// Output: "object
Functions in JavaScript:
A function is a reusable block of code designed to perform a
particular task.
It is executed when "something" invokes (calls) it.
Ways to Declare and Define Functions
Function Declaration (Statement):
The most common way, using the function keyword followed by a
name.
Syntax:
function name(parameters) { // body }
Example:
function multiply(a, b)
{
return a * b;
}
Function Expression:
Defining a function and assigning it to a variable.
The function can be anonymous (no name).
Syntax: const name = function(parameters) { // body };
Example:
const multiply = function(a, b) {
return a * b;
};
For example:
[Link]("The product is: " + multiply(10, 2));
// Output: The product is: 20
Ways of Calling (Invoking) a Function
Functions can be invoked in several ways:
Function Invocation (using parentheses): The most common way is calling
a function by its name followed by parentheses ().
function greet() {
[Link]("Hello!");
}
greet(); // Output: Hello!
Method Invocation: When a function is a property of an object, it's called
a method. It's invoked using dot notation (.).
const car = {
color: "Red",
start: function() {
[Link]("The car is starting...");
}
};
// Method Invocation:
[Link]();
Using call() and apply() methods: These methods allow you to invoke a function and
explicitly set the value of the ‘this’ keyword.
❑ call() takes arguments individually: [Link](thisArg, arg1, arg2, ...).
❑ apply() takes arguments as an array: [Link](thisArg, [argsArray]).
function introduce(age) {
[Link](`My name is ${[Link]} and I am ${age} years old.`);
}
const user = { name: “Asha" };
[Link](user, 30); // Output: My name is Asha and I am 30 years old.
[Link](user, [25]); // Output: My name is Asha and I am 25 years old.
Recursive Functions:
Recursive refers to a situation wherein functions call themselves. Such functions are called
as Recursive functions
Example: recursive function to calculate factorial
Function fact(number)
{
If (number>1)
{
return number* fact(number-1);
}
else
{
return number;
}
}
Conditional Constructs
Conditional statements are used to perform different actions based on different
conditions.
if statement: Executes code if a condition is true.
if-else statement: Executes one block if true, and another if false.
else if: Provides a new test if the first condition is false.
switch statement: Selects one of many code blocks to be executed.
Ternary Operator (? :): A shorthand for a simple if...else statement.
if statement: Executes a block of code if the specified condition is true.
if (5 > 2) {
[Link]("5 is greater than 2.");
}
if...else statement: Executes the if block if the condition is true, and the else block if the
condition is false.
let age = 18;
if (age >= 18) {
[Link]("You are an adult.");
} else {
[Link]("You are a minor.");
}
else if statement: Used to test multiple conditions sequentially.
let score = 75;
if (score >= 90) {
[Link]("Grade A");
} else if (score >= 70) {
[Link]("Grade B");
} else {
[Link]("Grade C or lower");
}
switch statement: Evaluates an expression and matches its value against a series of case
clauses, executing the associated code block. A break statement is crucial to prevent
"fall-through" to other cases. A default case runs if no match is found.
let day = "Monday";
switch (day) {
case "Monday":
[Link]("Start of the week");
break;
case "Friday":
[Link]("End of the week");
break;
default:
[Link]("Midweek day");
}
loops available in JavaScript
JavaScript provides several types of for loops for different iteration scenarios.
for loop (standard): Used when you want to repeat a block of code a specific number
of times. It combines initialization, a condition, and an update expression into a single
line.
Syntax:
for (initialization; condition; afterthought) {
// code block
}
Example:
for (let i = 0; i < 3; i++) {
[Link](i);
}
// Output: 0, 1, 2
for...in loop: Iterates over the enumerable properties (keys/indices) of an object.
Syntax:
for (variable in object) {
// code block
}
Example:
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
[Link](key + ": " + obj[key]);
}
// Output:
// a: 1
// b: 2
// c: 3
for...of loop: Iterates over the values of iterable objects (like Array, Map, Set, String, etc.).
Syntax:
for (variable of iterable) {
// code block
}
Example:
const arr = [10, 20, 30];
for (const value of arr) {
[Link](value);
}
// Output:
// 10
// 20
// 30
while Loop
The while loop checks the condition before executing the code block.
Syntax:
while (condition) {
// code to execute
}
Example:
let i = 1;
while (i <= 5) {
[Link](i);
i++;
}
do...while Loop
The do...while loop executes the code block first, then checks the condition.
Syntax:
do {
// code to execute
} while (condition);
Example:
let i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
Using break and continue:
The break and continue statements allow you to stop what a loop is currently doing,
but work in different ways.
the break statement stops the loop at that point and completely exits the loop, moving
on to the next JavaScript statement after the loop.
The continue statement:
The continue statement will stop the loop from executing any statements after it during
the current trip through the loop. However, it will go back to the beginning of the loop
and pick up where it left off, rather than exiting the loop entirely.
The result is that the “I am part of a loop!” message will be written to the page
only nine times.
Equal(==) vs Strictly equal(===)
The primary difference is that the equal (==) operator performs type
coercion (automatic type conversion) before comparison, while the strictly equal
(===) operator does not perform type coercion and requires both the value and the
type to be the same.
JavaScript Document Object Model
(DOM)
The Document Object Model (DOM) is a programming interface for web
pages.
It represents the HTML document as a tree structure of objects so that
JavaScript can access and modify the content, structure, and style of a
webpage dynamically.
Document Object Model represents this table
like this:
Object in HTML (DOM Objects)
HTML itself does not have “objects” like programming languages.
When an HTML page is loaded in a browser, it is converted into a
Document Object Model (DOM).
The DOM represents the HTML document as a collection of objects.
Each HTML element becomes an object.
For example:
<html> → HTML object
<body> → Body object
<p> → Paragraph object
What is an Object in HTML?
An object in HTML (DOM) is:
A representation of an HTML element
It contains:
Properties (data)
Methods (functions)
Events
Example
<p id="demo">Hello</p>
In JavaScript:
[Link]("demo")
Here:
document → Document object
getElementById() → Method
"demo" → ID of the HTML object
Common HTML DOM Objects
Document Object
Represents entire HTML page
Example: [Link]
Element Object
Represents HTML elements
Example: [Link]("demo").innerHTML
Form Object
Represents <form> element
Image Object
Represents <img> element
Anchor Object
Represents <a> element
Properties of HTML Objects (DOM Properties)
1️⃣ innerHTML Property
innerHTML gets or sets the HTML content inside an element.
It includes:
a. Text
b. HTML tags
c. Formatting
Example:
<p id="demo"></p>
[Link]("demo").innerHTML = "<b>Hello</b>";
2️⃣ innerText Property
innerText gets or sets only the visible text content of an element.
It ignores HTML tags.
Example:
[Link]("demo").innerText = "<b>Hello</b>";
Output:
<b>Hello</b> (It shows as plain text)
Because innerText does NOT interpret HTML tags.
3️⃣ style Property
The style property is used to change CSS styles of an element using JavaScript.
Example:
[Link]("demo").[Link] = "red";
[Link]("demo").[Link] = "20px";
Output:
Text becomes red and size 20px.
4️⃣ value Property
The value property is used with form elements like:
<input>
<textarea>
<select>
It gets or sets the value entered by the user.
Example:
<input type="text" id="name">
let userName = [Link]("name").value;
This stores the typed value in userName.
[Link]("name").value = "Megha";
DOM Methods
Methods for Selecting Elements
[Link]("idName"): Returns a single element with the specified ID.
[Link]("className"): Returns a live HTMLCollection of
elements with the given class name.
[Link]("p"): Returns a live HTMLCollection of elements with the
given tag name.
[Link]("#idName"): Returns the first element matching a CSS selector.
[Link](".className"): Returns a static NodeList of all elements matching
a CSS selector.
Example:
[Link]("demo").innerHTML = "Hello World!";
1️⃣ [Link]("idName")
Selects one single element with the specified ID.
IDs are always unique.
Example:
<p id="demo">Original Text</p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
Output:
Original Text → changes to → Hello World!
2️⃣ [Link]("className")
Selects all elements with the given class name.
Returns a live HTMLCollection.
“Live” means it updates automatically if the DOM changes.
Example:
<p class="text">First</p>
<p class="text">Second</p>
<script>
let elements = [Link]("text");
elements[0].[Link] = "red";
elements[1].[Link] = "blue";
</script>
Output:
First → red
Second → blue
3️⃣ [Link]("p")
Selects all elements with a specific tag name.
Returns a live HTMLCollection.
Example:
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
let para = [Link]("p");
para[0].innerHTML = "Updated Paragraph 1";
</script>
Output:
First paragraph text changes to Updated Paragraph 1
Example:
<p id="demo">Hello</p>
<p class="text">One</p>
<p class="text">Two</p>
<script>
[Link]("demo").innerHTML = "Hello World!";
[Link]("text")[0].[Link] = "red";
[Link]("p")[1].[Link] = "25px";
[Link](".text").[Link] = "yellow";
let allItems = [Link](".text");
allItems[1].innerHTML = "Updated Two";
</script>
Objects
JavaScript String Object
A String object in JavaScript is used to represent and manipulate textual data.
Strings can be created in two ways:
let str1 = "Hello"; // String literal
let str2 = new String("Hello"); // String object
String Properties
length → Returns number of characters.
Example:
let text = "JavaScript";
[Link]([Link]); // 10
String Methods
Method Description
charAt(index) Returns character at position
indexOf() Returns first occurrence
lastIndexOf() Returns last occurrence
toUpperCase() Converts to uppercase
toLowerCase() Converts to lowercase
substring() Extracts part of string
replace() Replaces text
trim() Removes whitespace
split() Converts string into array
let msg = "Welcome";
[Link]([Link]());
Window Object
The Window object is the top-level object. It represents the browser window.
Important Methods
alert()
confirm()
prompt()
open()
close()
setTimeout()
setInterval()
Method Purpose Syntax Example
alert() Displays a message box with OK button alert(message) alert("Welcome to JavaScript");
let result = confirm("Are you sure?");
Displays confirmation box with OK &
confirm() confirm(message) if(result){ alert("You clicked OK"); } else
Cancel (returns true/false) { alert("You clicked Cancel"); }
let name = prompt("Enter your name:",
prompt() Displays input box to get user input prompt(message, default) "Guest"); alert("Hello " + name);
open() Opens a new browser window/tab [Link](url) [Link]("[Link]
close() Closes current browser window [Link]() [Link]();
Executes function once after specified setTimeout(function(){ alert("Executed after
setTimeout() setTimeout(function,time)
time (milliseconds) 3 seconds"); }, 3000);
Executes function repeatedly at setInterval(function(){ [Link]("Runs
setInterval() setInterval(function,time)
specified interval every 2 seconds"); }, 2000);
Browser Object
The Browser Object Model allows JavaScript to interact with the browser.
Main Objects:
Window
Navigator
Screen
Important Properties /
Object Purpose Example
Methods
Represents the browser
alert(), open(),
Window window. It is the top-level [Link]("Welcome");
close(), setTimeout()
object in BOM.
[Link],
Provides information about [Link]([Link]
Navigator [Link],
the browser. rAgent);
[Link]
[Link],
Provides information about alert("Screen Width: " +
Screen [Link],
user’s screen. [Link]);
[Link]
Navigator Object
The Navigator object contains information about the browser.
Important Properties
[Link]
[Link]
[Link]
[Link]
[Link]
Example:
[Link]([Link]);
Built-in Objects in JavaScript
Object Purpose
Array Store multiple values
Math Mathematical operations
Date Date and time
Number Numeric operations
Boolean True/False
RegExp Pattern matching
Form Object
The Form object represents HTML forms.
Accessing forms:
[Link]["formName"]
Important Properties
action – Specifies where the form data is sent.
method – Specifies how the form data is sent (GET/POST).
Example
function validate() {
let name = [Link]["myForm"]["fname"].value;
if(name == "") {
alert("Name must be filled out");
return false;
}
}
User Defined Objects
Objects created by the programmer.
1. Object Literal 2. Constructor Function
let student = { function Student(name, age) {
name: "Megha", [Link] = name;
age: 24, [Link] = age;
display: function() {
return [Link]; }
} let s1 = new Student("Megha",
};
20);
Mostly used when creating one single object.
When we need to create many
Cookies in JavaScript
A cookie is a small piece of data stored in the user's
browser by a website.
Cookies are used to store information about the user so
that the web application can remember data between
different pages or visits.
Since HTTP is a stateless protocol, cookies help maintain
state management.
In general, Cookies are small text files stored in the
browser that help maintain user state and improve user
experience.
Need for Cookies
To remember user login details
Tostore user preferences (language,
theme)
To maintain session information
To track user activity
To store shopping cart items
How Cookies Work
User visits a website.
Server sends a cookie to the browser.
Browser stores the cookie.
Onfuture requests, the browser sends the cookie
back to the server.
Thus,cookies enable communication between
client and server across multiple requests.
Creating a Cookie in JavaScript
Cookies are created using [Link].
Syntax:
[Link] = "name=value; expires=date; path=path";
Example:
[Link] = "username=ABC; expires=Fri, 31 Dec 2026 [Link] UTC; path=/";
Reading a Cookie
[Link]([Link]);
Since multiple cookies are stored as a single string, we must split them to read individual
values.
Updating a Cookie
To update a cookie, set the same name again:
[Link] = "username=Admin; expires=Fri, 31 Dec 2026 [Link] UTC; path=/";
Deleting a Cookie
Set expiry date to past date:
[Link] = "username=; expires=Thu, 01 Jan 1970 [Link] UTC; path=/";
Event Handling in JavaScript
An event is an action performed by the user or browser (click, load, keypress, etc.).
Types of Events
Mouse Events (onclick, ondblclick)
Keyboard Events (onkeydown, onkeyup)
Form Events (onsubmit, onchange)
Window Events (onload, onresize)
Keyboard events:
❑ keydown : This event fires when a key is first pressed down and repeats if the key
is held down. It is widely used for actions like game controls or keyboard
shortcuts.
❑ keyup : This event occurs when a key that was previously pressed is released. It is
suitable for actions that should happen after a user finishes typing, such as form
validation or triggering search suggestions.
❑ keypress (Deprecated) : This event fires when a key producing a character
value (like a letter, number, or symbol) is pressed. It is not triggered for non-
character keys such as the Alt, Ctrl, Shift, or Escape keys.
❑ input : While not strictly a keyboard event, the input event is a modern and
reliable way to track any changes to the value of an <input>, <textarea>, or
<select> element, regardless of the input method (typing, copy/pasting, speech
recognition, etc.). It's often a better choice for tracking text input in form fields
than keyboard events.
Mouse Events
click: This event fires when a user presses and then releases the main
mouse button (usually the left button) over the same element.
mouseover: This event triggers when the mouse pointer moves onto an
element or any of its descendant elements. It is often used to show
additional information (like a tooltip) or change an element's
appearance when hovered over.
mousedown: This event fires the moment a user presses a mouse button
down over an element, regardless of whether it is released. This event
gives developers more control for interactions such as drag-and-drop
operations that need to begin as soon as the button is pressed.
mousemove: This event fires continuously as the mouse pointer is
moved over an element. It is useful for implementing custom drag
features.
Ways to Handle Events
1. Inline Event Handling
<button onclick="alert('Clicked!')">Click</button>
2. Using JavaScript
[Link]("btn").onclick = function() {
alert("Clicked");
}
3. addEventListener() (Recommended)
[Link]("btn").addEventListener("click", function(){
alert("Clicked");
});