Unit-IV:-JavaScript
Document Object Model
The Document Object Model (DOM) is a cross-
platform and language-independent API that treats
an HTML or XML document as a tree structure wherein
each node is an object representing a part of the document. The
DOM represents a document with a logical tree. Each branch of
the tree ends in a node, and each node contains objects. DOM
methods allow programmatic access to the tree; with them one
can change the structure, style or content of a document. Nodes
can have event handlers (also known as event listeners)
attached to them. Once an event is triggered, the event handlers
get executed
3
4
Introduction to JavaScript
JavaScript is a versatile, dynamically typed programming
language that brings life to web pages by making them
interactive. It is used for building interactive web applications,
supports both client-side and server-side development, and
integrates seamlessly with HTML, CSS, and a rich standard
library.
5
6
• JavaScript is a single-threaded language that executes one
task at a time.
• It is an interpreted language which means it executes the code
line by line.
• The data type of the variable is decided at run-time in
JavaScript, which is why it is called dynamically typed
7
"Hello, World!" Program in Browser
Console
<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
[Link]("Hello, World!");
</script>
</body>
</html>
8
JavaScript Variables
• Variables in JavaScript can be declared using var, let, or const.
JavaScript is dynamically typed, so variable types are determined at
runtime without explicit type definitions.
var a = 10 // Old style
let b = 20; // Preferred for non-const
const c = 30; // Preferred for const (cannot be changed)
[Link](a);
[Link](b);
[Link](c);
9
Rules for Naming Variables
• When naming variables in JavaScript, follow these rules
• Variable names must begin with a letter, underscore (_), or
dollar sign ($).
• Subsequent characters can be letters, numbers, underscores,
or dollar signs.
• Variable names are case-sensitive (e.g., age and Age are
different variables).
• Reserved keywords (like function, class, return, etc.) cannot
be used as variable names.
10
let userName = "Suman"; // Valid
let $price = 100; // Valid
let _temp = 0; // Valid
let 123name = "Ajay"; // Invalid
let function = "gfg"; // Invalid
11
JavaScript String Manipulation
Techniques
• Strings play a vital role in any programming language.
Properly understanding string manipulation techniques can
help developers easily handle tricky situations.
• In JavaScript, strings are immutable and help us to store text
that includes characters, numbers, and Unicode. Also,
JavaScript includes many built-in functions for creating and
manipulating strings in various ways.
12
split()
The split() method divides a string into an ordered list of two or more substrings and returns
it, depending on the pattern, divider, or delimiter provided.
let quote = 'I am Dhrubo Das’;
// Split string using the space character
let array1 = [Link](' ');
[Link](array1);
// Output: ["I", "am", "Dhrubo", "Das"]
// Split string using an empty string (on each character)
let array2 = [Link]('');
[Link](array2);
// Output: ["I"," ","a","m"," ","D","h","r","u","b","o"," ",
"D","a","s"]
13
from()
The from() method of the Array class is the leading competitor for the split() method. It allows us to make an
array from a data source. We can also use this to make an array from an iterable string.
let name = "Dhrubo Das";
// String to array of characters
let nameChars = [Link](name);
[Link](nameChars);
// Output:
[ 'D', 'h', 'r', 'u', 'b', 'o', ' ', 'D', 'a', 's']
14
Spread operator (…)
The spread operator is another JavaScript feature that helps us to create an array from a
string.
let name = "Dhrubo Das";
// Spread out string into an array
let nameChar = [...name];
[Link](nameChar);
// [ 'D', 'h', 'r', 'u', 'b', 'o', ' ', 'D', 'a', 's']
Check for a specific sequence in a string 15
Similar to splitting, there are many ways to check for a specific sequence in a JavaScript
string. The includes() method, indexOf(), or a regular expression can be used for such
purposes. However, includes() is the most frequently used method for determining whether
a string contains a letter or series of letters. It was specifically created for that purpose .
const text = "Hi, This is Hello World“
[Link]([Link](“is"));
// true
[Link]([Link](“Other"));
// false
16
Check if a string starts or ends with a
specific sequence
startsWith() determines whether a string begins with a specific substring. It will return true if the string begins with
the specified substring. Otherwise, it returns false.
const text = "Hi, My name is Dhrubo"
[Link]([Link]("Hi"));
// true
17
The endsWith() method allows us to determine
whether a string ends with a specified string.
const text = "Hi, My name is Dhrubo“
[Link]([Link]("Hi"));
// false
18
Split a string on multiple separators
// Split on comma (,) and semicolon (;).
const list = "Car,Bus;Train"
const vehicles= [Link](/[,;]/);
[Link](vehicles);
// ["Car", "Bus", "Train"]
19
Reverse characters in a string
const word = “Dhrubo";
const reversedWord = [...word].reverse().join("");
[Link](reversedWord);
// “oburhD"
20
Copy a string multiple times
/ Concatenate "0" 10 times.
const zeroString= "0".repeat(10);
[Link](zeroString);
// "0000000000"
21
Pad a string to a specific length
Use the padStart() and padEnd() methods to pad your string at
the beginning or end.
// Add 0 to the beginning until the string has a length of 10.
const string = "001".padStart(10, "0");
[Link](string); // "0000000001"
// Add * to the end until the string has a length of 10.
const string = "99".padEnd(10, "*");
[Link](string ); // "99********"
22
Count characters in a string
const word = "Dhrubo Das";
[Link]([Link]);
// 10
23
Converting a letter in a string to
uppercase or lowercase
To Uppercase
let name = " Dhrubo";
name = name[0].toUpperCase() + [Link](1);
[Link](name); // “DHRUBO"
To Lowercase
name = name[0].toLowerCase() + [Link](1);
[Link](name); // “dhrubo"
24
Replace all occurrences of a string
const text = "I like Cars. Cars have 4 wheels"
[Link]([Link](/Cars/g, "Vans"));
// "I like Vans. Vans have 4 wheels"
[Link]([Link]("Cars", "Vans"));
// "I like Vans. Vans have 4 wheels"
25
JavaScript Math Object
• [Link]("Math.LN10: " + Math.LN10);
• [Link]("Math.LOG2E: " + Math.LOG2E);
• [Link]("Math.Log10E: " + Math.LOG10E);
• [Link]("Math.SQRT2: " + Math.SQRT2);
• [Link]("Math.SQRT1_2: " + Math.SQRT1_2);
• [Link]("Math.LN2: " + Math.LN2);
• [Link]("Math.E: " + Math.E);
• [Link]("[Link]: " + [Link]);
26
Output
Math.LN10: 2.302585092994046
Math.LOG2E: 1.4426950408889634
Math.Log10E: 0.4342944819032518
Math.SQRT2: 1.4142135623730951
Math.SQRT1_2: 0.7071067811865476
Math.LN2: 0.6931471805599453
Math.E: 2.71828...
27
• [Link]("[Link](-4.7): " + [Link](-4.7));
• [Link]("[Link](4.4): " + [Link](4.4));
• [Link]("[Link](4.7): " + [Link](4.7));
• [Link]("[Link](90 * [Link] / 180): " + [Link](90
[Link] / 180));
• [Link]("[Link](0, 150, 30, 20, -8, -200): " +
[Link](0, 150, 30, 20, -8, -200));
• [Link]("[Link](): " + [Link]());
28
[Link](-4.7): 4.7
[Link](4.4): 5
[Link](4.7): 4
[Link](90 * [Link] / 180): 1
[Link](0, 150, 30, 20, -8, -200): -200
[Link](): 0.7416861489868538
29
JavaScript Operators
30
1. JavaScript Arithmetic Operators
• const sum = 5 + 3; // Addition
• const diff = 10 - 2; // Subtraction
• const p = 4 * 2; // Multiplication
• const q = 8 / 2; // Division
• [Link](sum, diff, p, q);
8884
31
2. JavaScript Assignment Operators
let n = 10;
n += 5;
n *= 2;
[Link](n);
O/P:- 30
32
3. JavaScript Comparison Operators
[Link](10 > 5);
[Link](10 == "10");
• True
• False
33
4. JavaScript Logical Operators
const a = true, b = false;
[Link](a && b); // Logical AND F
[Link](a || b); // Logical OR T
34
5. JavaScript Bitwise Operators
const res = 5 & 1; // Bitwise AND
[Link](res);
• O/p :- 1
35
6. JavaScript Ternary Operator
const age = 18;
const status = age >= 18 ? "Adult" : "Minor";
[Link](status);
O/p
Adult
36
7. JavaScript Comma Operator
let n1, n2
const res = (n1 = 1, n2 = 2, n1 + n2);
[Link](res);
• Output
3
37
8. JavaScript Unary Operators
let x = 5;
[Link](++x); // Pre-increment
[Link](x--); // Post-decrement (Output: 6, then x becomes
5)
• Output
• 6
• 6
38
9. JavaScript Relational Operators
const obj = { length: 10 };
[Link]("length" in obj);
[Link]([] instanceof Array);
• Output
• true
• true
39
10. JavaScript BigInt Operators
const big1 = 123456789012345678901234567890n;
const big2 = 987654321098765432109876543210n;
[Link](big1 + big2);
• Output
• 1111111110111111111011111111100n
40
11. JavaScript String Operators
const s = "Hello" + " " + "World";
[Link](s);
• Output
• Hello World
41
12. JavaScript Chaining Operator (?.)
const obj = { name: "Aman", address: { city: "Delhi" } };
[Link]([Link]?.city);
[Link]([Link]?.phone);
• Output
Delhi
undefined
42
JavaScript Arrays
In JavaScript, an array is a global object used to store an ordered collection of values under a single variable
name. Key characteristics and functionalities of JavaScript arrays include:
•Creation:
Arrays can be created using array literals (e.g., let arr = [1, 2, 3];) or the Array constructor
(e.g., let arr = new Array(1, 2, 3);).
•Zero-Indexed:
Array elements are accessed using numerical indices, starting from 0 for the first element. For example,
arr[0] refers to the first element.
•Resizable and Mixed Data Types:
JavaScript arrays are dynamic, meaning their size can change, and they can store elements of different
data types within the same array (e.g., numbers, strings, objects).
•Shallow Copies:
Standard built-in array copy operations (like slice()) create shallow copies, meaning nested objects are
still referenced by both the original and new array.
43
Methods:
JavaScript provides numerous built-in methods for manipulating arrays, including:
•Adding/Removing Elements: push(), pop(), shift(), unshift(), splice().
•Iterating: forEach(), map(), filter(), reduce().
•Searching: indexOf(), lastIndexOf(), find(), findIndex(), includes().
•Transforming: sort(), reverse(), join(), slice(), concat().
•Newer Methods (ES2022+): at() for accessing elements with negative indexing,
•toReversed() for non-mutating reversal.
44
// Creating an array
let fruits = ["Apple", "Banana", "Orange"];// Accessing elements
[Link](fruits[0]); // Output: Apple
// Adding an element
[Link]("Mango");
[Link](fruits); // Output: ["Apple", "Banana", "Orange", "Mango"]
// Iterating with forEach
[Link](function(fruit) {
[Link]([Link]());
});
45
JavaScript Function and Function
Expressions
• A function is an independent block of code that performs a
specific task, while a function expression is a way to store
functions in variables.
• Here, we created the greet() function and used the displayPI
variable to create a function expression. Then, we called the
functions by using their names followed by parentheses () i.e.
greet() and displayPI().
46
// create a function named greet()
function greet() {
[Link]("Hello World!");
}
// store a function in the displayPI variable this is a function expression
let displayPI = function() {
[Link]("PI = 3.14");
}
// call the greet() function
greet();
// call the reply() function
displayPI ();
// Output:
// Hello World!
// PI = 3.14
47
Create a JavaScript Function
function greet() {
[Link]("Hello World!");
}
48
49
Here, we have created a simple function named greet() that prints Hello World! on the screen.
Our function contains the following parts:
•Function Keyword - The function keyword is used to create the function.
•Function Name - The name of the function is greet, followed by parentheses ().
•Function Body - The code that is executed when we call the function. In our case, it is [Link]("Hello World!");
50
Call a Function
function greet() {
[Link]("Hello World!");
}
greet();
51
JavaScript Function Call
// create a function
function greet() {
[Link]("Hello World!");
}
// call the function
greet();
[Link]("Outside function");
Output
Hello World!
Outside function
52
Objects in JavaScript
What is an Object?
An object in JavaScript is a collection of key-value pairs where
each key is a string (or Symbol), and the value can be any
data type including functions.
53
Syntax
let person = {
firstName: "John",lastName: "Doe",age: 30,
greet: function () {
return "Hello " + [Link];
}
};
54
Accessing Object Properties
[Link]; // Dot notation
person["lastName"]; // Bracket notation
55
Adding / Modifying Properties
[Link] = "Male"; // Add
[Link] = 35; // Modify
• Deleting Properties:-
delete [Link];
56
Object Methods:-
Functions defined inside objects are called methods.
let car = {
brand: "Toyota",
start: function ()
{
[Link]("Engine started");
}
};
[Link](); // Call method
57
Built-in Object Methods
•[Link](obj) – returns an array of keys
•[Link](obj) – returns an array of values
•[Link](obj) – returns array of [key, value] pairs
•[Link](target, source) – copies properties
58
Nested Objects
let student = {
name: "Alice",
address: {
city: "New York",
zip: 10001
}
};
[Link]([Link]); // Output: New York
59
Example Use Cases
1. Validate Email
let email = "test@[Link]";
let pattern = /^[\w.-]+@[\w.-]+\.\w+$/;
[Link]([Link](email)); // true
60
2. Match digits
let str = "User123";
[Link]([Link](/\d+/g)); // ["123"]
3. Replace content
let text = "I love cats";
let newText = [Link](/cats/,"dogs");
[Link](newText); // "I love dogs"
61
Data Validation in JavaScript
• Data Validation is the process of ensuring that user input is
accurate, complete, and follows specific rules before being
processed or stored.
• Validation can be done:
• Client-side (using JavaScript)
• Server-side (using backend scripts)
62
Example: Form with JavaScript Validation
Sample HTML Form
<form onsubmit="return validateForm()">
Name: <input type="text" id="name"><br>
Email: <input type="text" id="email"><br>
Age: <input type="number" id="age"><br>
<input type="submit" value="Submit">
</form>
<p id="errorMsg" style="color:red;"></p>
63
Messages & Confirmation in JavaScript
• JavaScript provides built-in dialog boxes that allow you to
interact with users by displaying messages or getting
confirmations/inputs. These are:
• Alert Box
• Confirm Box
• Prompt Box
64
1. Alert Box
Purpose:
Used to display a message to the user. It only has an OK button.
Syntax:
alert("This is an alert message!");
Example:
alert("Form submitted successfully!");
•Blocks execution until user clicks "OK"
•Good for simple notifications and warnings
65
2. Confirm Box
Purpose:
Used to ask for confirmation from the user. Has OK and Cancel buttons.
Syntax:
let result = confirm("Are you sure you want to delete?");
Example:
if (confirm("Do you want to log out?")) {
// OK clicked
[Link]("Logged out");
} else {
// Cancel clicked
[Link]("Cancelled"); }
Returns:
•true if user clicks OK
•false if user clicks Cancel
66
3. Prompt Box
Purpose:
Used to get input from the user.
Syntax:
let input = prompt("What is your name?");
Example:
let age = prompt("Enter your age:");
if (age !== null) {
alert("Your age is " + age);
} else {
alert("Input was cancelled"); }
Returns:
•The user input (as a string)
•null if the user presses Cancel
67
Basic programs
1. JavaScript Program to Add Two Numbers.
2. JavaScript Program Check if a Number is Odd or Even.
3. JavaScript program to Swap Two Variables in
JavaScript.
4. JavaScript Program to Check if a number is Positive,
Negative, or Zero
68
Solution of 1.
let num1 = 10;
let num2 = 10;
let sum = num1 + num2;
[Link]("Sum :", sum);
69
Solution of 2.
function isEven(n) {
return (n % 2 == 0);
}
let n = 101;
isEven(n) ? [Link]("Even") : [Link]("Odd");
70
3:-
let a = 40;
let b = 30;
[Link](`before swap a= ${a}`);
[Link](`before swap b= ${b}`);
// a would be swapped to b and b would be swapped to a
[b, a] = [a, b];
[Link](`after swap a= ${a}`);
[Link](`after swap b= ${b}`);
71
4:-
function numberChecking(num) {
switch ([Link](num)) {
case 1:
[Link]("The number is Positive");
break;
case -1:
[Link]("The number is Negative");
break;
default:
[Link]("The number is Zero");
} }numberChecking(12);
// Output: Positive
A.B. Road, Pigdamber, Rau, Indore – 453331
0731 3111500, 0731 3111501
[Link]