UNIT 2 JavaScript
UNIT 2 JavaScript
UNIT 2 JavaScript
Introduction:-
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.
Features of JavaScript
Here are some key features of JavaScript that make it a powerful language for
web development:
Client-Side Scripting: JavaScript runs on the user's browser, so has a faster
response time without needing to communicate with the server.
Versatile: Can be used for a wide range of tasks, from simple calculations to
complex server-side applications.
Event-Driven: Responds to user actions (clicks, keystrokes) in real-time.
Asynchronous: It can handle tasks like fetching data from servers without
freezing the user interface.
Rich Ecosystem: There are numerous libraries and frameworks built on
JavaScript, such as React, Angular, and [Link], which make development
faster and more efficient.
Definition:-
"The Document Object Model (DOM) is a platform and language-neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style of a
document."
The HTML Document Object Model (DOM) is a tree structure, where each
HTML tag becomes a node in the hierarchy.
At the top, the <html> tag is the root element, containing
both <head> and<body> as child elements.
These in turn have their own children, such as <title>, <div>, and nested
elements like <h1>, <p>,<ul>, and<li>.
Elements that contain other elements are labeled as container elements, while
elements that do not are simply child elements.
This hierarchy allows developers to navigate and manipulate web page
content using JavaScript by traversing from parent to child and vice versa.
Properties of the DOM
Node-Based: Everything in the DOM is represented as a node (e.g., element
nodes, text nodes, attribute nodes).
Types of DOM
The DOM is seperated into 3 parts:
Core DOM: It is standard model for all document types(All DOM
implementations must support the interfaces listed as "fundamental" in the
code specifications).
XML DOM: It is standard model for XML Documents( as the name suggests,
all XML elements can be accessed through the XML DOM .)
HTML DOM: It is standard model for HTML documents (The HTML DOM
is a standard for how to get, change, add, or delete HTML elements.)
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.
// Old style
var a = 10
[Link](a);
[Link](b);
[Link](c);
Output
10
20
30
ES6 Introduction: let and const were introduced to provide safer alternatives for
declaring variables.
Scope: let and const are block-scoped (limited to { } block) or global-scoped,
reducing errors compared to var.
1. var keyword
var is a keyword in JavaScript used to declare variables and it is Function-
scoped and hoisted, allowing redeclaration but can lead to unexpected bugs.
var a = "Hello Geeks";
var b = 10;
[Link](a);
[Link](b);
2. let keyword
let is a keyword in JavaScript used to declare variables and it is Block-scoped and
not hoisted to the top, suitable for mutable variables
let a = 12
let b = "gfg";
[Link](a);
[Link](b);
3. const keyword
const is a keyword in JavaScript used to declare variables and it is Block-scoped,
immutable bindings that can't be reassigned, though objects can still be mutated.
const a = 5
let b = "gfg";
[Link](a);
[Link](b);
specific properties and behavior that impact how data is stored, accessed,
and manipulated.
let n2 = 1.3;
[Link](n2)
let n3 = Infinity;
[Link](n3)
Output
2
1.3
Infinity
NaN
2. String
A String in JavaScript is a series of characters that are surrounded by quotes.
There are three types of quotes in JavaScript, which are.
let s1 = "Hello There";
[Link](s1);
Output
Hello There
Single quotes work fine
can embed Hello There
There's no difference between 'single' and "double" quotes in JavaScript.
Backticks provide extra functionality as with their help of them we can embed
variables inside them.
3. Boolean
The boolean type has only two values i.e. true and false.
let b1 = true;
[Link](b1);
let b2 = false;
[Link](b2);
Output
true
false
4. Null
The special null value does not belong to any of the default data types. It forms a
separate type of its own which contains only the null value.
let age = null;
[Link](age)
Output
null
The 'null' data type defines a special value that represents nothing, or empty
value.
5. Undefined
A variable that has been declared but not initialized with a value is automatically
assigned the undefined value. It means the variable exists, but it has no value
assigned to it.
let a;
[Link](a);
Output
undefined
Output
false
Output
Company
2. Arrays
An Array is a special kind of object used to store an ordered collection of values,
which can be of any data type.
let a1 = [1, 2, 3, 4, 5];
[Link](a1);
Output
[ 1, 2, 3, 4, 5 ]
[ 1, 'two', { name: 'Object' }, [ 3, 4, 5 ] ]
3. Function
A function in JavaScript is a block of reusable code designed to perform a
specific task when called.
// Defining a function to greet a user
function greet(name) { return "Hello, " + name + "!"; }
// Calling the function
[Link](greet("Ajay"));
Output
Hello, Ajay!
4. Date Object
The Date object in JavaScript is used to work with dates and times, allowing for
date creation, manipulation, and formatting.
// Creating a new Date object for the
// current date and time
let currentDate = new Date();
Output
2025-03-08T06:23:33.202Z
5. Regular Expression
A RegExp (Regular Expression) in JavaScript is an object used to define search
patterns for matching text in strings.
// Creating a regular expression to match the word "hello"
let pattern = /hello/;
[Link](result);
Output
false
JavaScript - Operators
In JavaScript, an operator is a symbol that performs an operation on one or more operands,
such as variables or values, and returns a result. Let us take a simple expression 4 + 5 is equal
to 9. Here 4 and 5 are called operands, and + is called the operator.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Bitwise Operators
Assignment Operators
Miscellaneous Operators
z=x
= (Simple + y
Assigns values from the right side operand to the left side operand will
Assignment)
assign the
value of x
+ y
into z
z +=
+= (Add x is
It adds the right operand to the left operand and assigns the result to
and equivalent
the left operand.
Assignment) to z = z
+ x
z -= x is
= (Subtract and It subtracts the right operand from the left operand and assigns the equivalent
Assignment) result to the left operand. to z = z -
x
z *=
*=(Multiply x is
It multiplies the right operand with the left operand and assigns the
and equivalent
result to the left operand.
Assignment) to z = z
* x
z /= x is
/= (Divide and It divides the left operand with the right operand and assigns the equivalent
Assignment) result to the left operand. to z = z /
x
z %= x is
%= (Modules
It takes modulus using two operands and assigns the result to the left equivalent
and
operand. to z = z %
Assignment)
x
In the below table, we have given the JavaScript miscellaneous operators with its
explanation.
Operator Description
1: If Statement
In this approach, we are using an if statement to check a specific condition, the
code block gets executed when the given condition is satisfied.
Syntax
if ( condition_is_given_here ) {
// If the condition is met,
//the code will get executed.
}
Now let's understand this with the help of example:
const num = 5;
if (num > 0) {
[Link]("The number is positive.");
};
Output
The number is positive.
if (num > 0)
[Link]("The number is positive.");
else
[Link]("The number is negative");
Output
The number is negative
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Now let's understand this with the help of example:
let num = 5;
switch (num) {
case 0:
[Link]("Number is zero.");
break;
case 1:
[Link]("Nuber is one.");
break;
case 2:
[Link]("Number is two.");
break;
default:
[Link]("Number is greater than 2.");
};
Output
Number is greater than 2.
Output
The number is Positive.
Output
0
2
4
6
8
10
while (i <= 5) {
[Link](i);
i++;
}
Output
1
2
3
4
5
do {
[Link](i);
i++;
} while (i <= 5);
Output
1
2
3
4
5
Syntax:
[Link](element_ID);
Parameter:
It takes the ID of the element which the user wants to access.
Return value:
It returns the object with the particular ID. If the element with the particular ID
isn't found, it returns the NULL value.
Example: This example demonstrates the use of the getElementsById method.
Also, it prints the inner HTML of a returned object into the console of the
browser. Users can open the console in the Chrome web browser by pressing ctrl
+ shift + I.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<!-- Heading element with GeeksforGeeks id-->
<h1 id="Geeksforgeeks">
GeeksforGeeks
</h1>
<p>DOM getElementById() Method</p>
<script>
// Accessing the element by getElementById method
let temp = [Link]("Geeksforgeeks");
[Link](temp);
[Link]([Link]);
</script>
</body>
</html>
Output:
access an element using the className, it returns the collection of all objects that
include a particular class.
Syntax:
[Link](element_classnames);
Parameter:
It takes the multiple class names of the element which the user wants to access.
Return value:
It returns the collection of objects that have a particular class name. Users can get
every element from the collection object using the index that starts from 0.
Example 1: This example demonstrates the use of
the getElementsByClassName() method. It prints every element of the returned
collection object into the console. Users can open the console in the Chrome web
browser by pressing ctrl + shift + I.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<!-- Multiple html element with GeeksforGeeks class name -->
<h1 class="GeeksforGeeks">GeeksforGeeks sample 1</h1>
<h1 class="GeeksforGeeks">GeeksforGeeks sample 2</h1>
<h1 class="GeeksforGeeks">GeeksforGeeks sample 3</h1>
JavaScript Events
JavaScript Events are actions or occurrences that happen in the browser. They
can be triggered by various user interactions or by the browser itself.
<html>
<script>
function myFun() {
[Link](
"gfg").innerHTML = "GeeksforGeeks";
}
</script>
<body>
<button onclick="myFun()">Click me</button>
<p id="gfg"></p>
</body>
</html>
The onclick attribute in the <button> calls the myFun() function when clicked.
The myFun() function updates the <p> element with id="gfg" by setting its
innerHTML to "GeeksforGeeks".
Initially, the <p> is empty, and its content changes dynamically on button
click.
Event Types
JavaScript supports a variety of event types. Common categories include:
Mouse Events: click, dblclick, mousemove, mouseover, mouseout
Keyboard Events: keydown, keypress, keyup
Form Events: submit, change, focus, blur
Window Events: load, resize, scroll
1. onClick ()-
The onclick event in JavaScript is triggered when a user clicks on an HTML element. It is commonly
used to execute a function when a button or other clickable element is clicked.
<script>
function showMessage() {
alert("Button clicked!");
}
</script>
</body>
</html>
2. onBlur()
The HTML DOM onblur event occurs when an object loses focus.
The onblur event is the opposite of the onfocus event. The onblur event is
mostly used with form validation code (e.g. when the user leaves a form field).
In HTML:
<element onblur="myScript">
<!DOCTYPE html>
<html lang="en">
<body>
Email:
<input type="email" id="email" onblur="myFunction()">
<script>
function myFunction() {
alert("Focus lost");
}
</script>
</body>
</html>
In JavaScript:
[Link] = function(){myScript};
<!DOCTYPE html>
<html lang="en">
<body>
<input type="email" id="email">
<script>
[Link]("email").onblur = function () {
myFunction()
};
function myFunction() {
alert("Input field lost focus.");
}
</script>
</body>
</html>
In JavaScript, using the addEventListener() method:
[Link]("blur", myScript);
<!DOCTYPE html>
<html lang="en">
<body>
<input type="email" id="email">
<script>
[Link](
"email").addEventListener("blur", myFunction);
function myFunction() {
alert("Input field lost focus.");
}
</script>
</body>
</html>
3. onFocus
The onfocus event in JavaScript is triggered when an element gains focus — typically when a
user clicks into an input field, tabs into it, or focuses it programmatically.
It’s commonly used with form elements like <input>, <textarea>, <select>, and <button>.
Key Points
Does not bubble: Unlike focusin, the focus/onfocus event does not bubble up the DOM.
Usage in HTML
You can use the onfocus attribute directly within an HTML element to specify the script to be executed
when the element gains focus. Here is an example:
<input type="text" onfocus="myFunction()">
In this example, the myFunction function will be called when the input field receives focus.
Usage in JavaScript
In JavaScript, you can assign a function to the onfocus property of an element or use
the addEventListener method to attach an event handler. Here are examples of both approaches:
// Using the onfocus property
[Link]("myInput").onfocus = function() {
myFunction();
};
// Using addEventListener
[Link]("myInput").addEventListener("focus", myFunction);
In both cases, the myFunction function will be executed when the input field with the
ID myInput receives focus
4. onKeyPress()
Whenever a key is pressed or released, there are certain events that are triggered.
Each of these events has a different meaning and can be used for implementing
certain functionalities depending on the current state and the key that is being
used.
These events that are triggered when a key is pressed are in the following order:
keydown Event: This event occurs when the user has pressed down the key.
It will occur even if the key pressed does not produce a character value.
keypress Event: This event occurs when the user presses a key that produces
a character value. These include keys such as the alphabetic, numeric, and
punctuation keys. Modifier keys such as 'Shift', 'CapsLock', 'Ctrl' etc. do not
produce a character, therefore they have no 'keypress' event attached to them.
keyup Event: This event occurs when the user has released the key. It will
occur even if the key released does not produce a character value.
Note that different browsers may have different implementations of the above
events. The onKeyDown, onKeyPress, and onKeyUp events can be used to
detect these events respectively.
Example: The below example shows different events that get triggered when a
key is pressed in their respective order.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p>
<b>onKeyPress Vs. onKeyUp
and onKeyDown Events</b>
</p>
<script>
let key_pressed =
[Link]('field');
key_pressed
.addEventListener("keydown", onKeyDown);
key_pressed
.addEventListener("keypress", onKeyPress);
key_pressed
.addEventListener("keyup", onKeyUp);
function onKeyDown(event) {
[Link]("status")
.innerHTML = 'keydown: '
+ [Link] + '<br>'
}
function onKeyPress(event) {
[Link]("status")
.innerHTML += 'keypress: '
+ [Link] + '<br>'
}
function onKeyUp(event) {
[Link]("status")
.innerHTML += 'keyup: '
+ [Link] + '<br>'
}
</script>
</body>
</body>
</html>
1. Alert Box
The alert box is the simplest type of dialogue box. It is used to display a message
to the user, typically for informational purposes. It contains only a message and an
OK button that the user can click to close the box.
How It Works
When the alert() function is called, the browser will display a pop-up box with
your specified message.
The user must click the OK button to close the box and continue interacting
with the webpage.
<html>
<head></head>
<body>
<script type="text/javascript">
function Warning() {
alert("Warning danger you have not filled everything");
[Link]("Warning danger you have not filled everything");
}
</script>
<p>Click the button to check the Alert Box functionality</p>
<form>
<input type="button" value="Click Me" onclick="Warning();" />
</form>
</body>
</html>
Output:
2. Confirm box
The confirm box is slightly more advanced than the alert box. It asks the user for
confirmation with two buttons: OK and Cancel. Based on the user's choice, we can
take specific actions.
How It Works
When the confirm() function is called, the browser displays a pop-up box with
the message and two options: OK and Cancel.
If the user clicks OK, the function returns true.
If the user clicks Cancel, the function returns false.
Use the returned value (true or false) to perform different actions based on the
user's choice. <script type="text/javascript">
function Confirmation() {
var Val = confirm("Do you want to continue ?");
if (Val == true) {
[Link](" CONTINUED!");
return true;
} else {
[Link]("NOT CONTINUED!");
return false;
}
}
</script>
3. Prompt Box
The prompt box allows you to ask the user for input. It provides a text field where
the user can enter data and a OK and Cancel button. You can use this to collect
information from the user, like their name, age, or email.
How It Works
When the prompt() function is called, a pop-up appears with a text field, and
the user is asked to input something.
If user can click OK, the text they entered is returned as a string. If user click
Cancel the function returns null.
Use the value returned by prompt() for any further logic, such as displaying it
on the webpage or processing it in other ways. <script type="text/javascript">
function Value(){
var Val = prompt("Enter your name : ", "Please enter your name");
[Link]("You entered : " + Val);
}
</script>
In this example
Button: There’s a "Click Me" button.
Function: Clicking the button calls the Value() function.
Prompt Box: A pop-up asks the user to "Enter your name."
User Input: Whatever the user types is saved in the Val variable.
Console Log: The entered name is logged in the console with the message
"You entered: [name]."
Displays
Asks for user confirmation Collects user input
information
Return value is Return value is true (OK) or Return value is User's input
none false (Cancel) (string) or null
Show simple
Ask for confirmation (Yes/No) Collect user input (text)
messages