Unit II – JavaScript
UNIT – II
JAVASCRIPT
Introduction to JavaScript – Variables – Data Types – Operators – Functions – DOM Manipulation –
Events – ES6 Features (Arrow Functions, Let/Const, Template Literals) – Promises – Async/Await.
1. Introduction to JavaScript
JavaScript is a high-level, interpreted programming language that was created in 1995 by
Brendan Eich and has since become the standard scripting language of the web. While HTML
defines the structure of a page and CSS defines its appearance, JavaScript defines its behavior,
the layer that makes a page interactive instead of just a static document. JavaScript code is
executed by a JavaScript engine built into every modern browser (for example, V8 in Chrome
and [Link], or SpiderMonkey in Firefox), so no separate compiler or plugin is required to run it.
1.1 Key Characteristics of JavaScript
• Interpreted/JIT-compiled language: Code is executed line by line by the browser's engine
rather than being compiled ahead of time into machine code.
• Dynamically typed: Variable types are determined automatically at runtime and can
change as a program runs.
• Single-threaded with an event loop: JavaScript executes one operation at a time but uses
an event loop to handle asynchronous tasks such as timers and network requests without
blocking the page.
• Object-based: Almost everything in JavaScript, including functions and arrays, is treated
as an object.
• Cross-platform: The same JavaScript code can run in any browser, on servers using
[Link], and even in mobile or desktop applications.
1.2 Where JavaScript Can Be Used
• Client-side scripting: Running inside the browser to validate forms, update content, and
respond to user actions.
• Server-side scripting: Using [Link] to build APIs, web servers, and backend services.
• Mobile and desktop apps: Frameworks such as React Native (mobile) and Electron
(desktop) are built using JavaScript.
• Game development: Libraries such as Phaser allow browser-based games to be built
entirely in JavaScript.
1.3 Adding JavaScript to a Web Page
• Inline: Placing JavaScript directly inside an HTML attribute, such as an onclick handler.
Not recommended for larger code.
• Internal: Writing JavaScript inside a script tag within the same HTML file, usually just
before the closing body tag.
1
Unit II – JavaScript
• External: Writing JavaScript in a separate .js file and linking it from the HTML page.
This is the most maintainable approach since it separates logic from structure and allows
the file to be reused and cached.
Real-Time Example
Online shopping websites such as Amazon and Flipkart use JavaScript extensively on the client
side: when a user adds an item to the cart, the cart icon and total price update instantly without
reloading the entire page. This instant, on-page update is only possible because JavaScript is
running in the browser and modifying the page in real time.
Sample Program: First JavaScript Program
<!DOCTYPE html>
<html>
<head>
<title>Introduction to JavaScript</title>
</head>
<body>
<h2>JavaScript Demo</h2>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello, JavaScript!";
[Link]("This message appears in the browser console.");
</script>
</body>
</html>
2. Variables
A variable is a named container used to store a data value so that it can be used and changed later
in a program. JavaScript provides three keywords for declaring variables: var, let, and const. var
has existed since the earliest version of JavaScript, while let and const were introduced in ES6
(2015) to make variable behavior more predictable and reduce common bugs.
2.1 var — The Original Declaration Keyword
Variables declared with var are function-scoped (or globally scoped if declared outside a
function), not block-scoped. This means a var declared inside an if block or a for loop is still
accessible outside that block, as long as it is within the same function. var variables are also
hoisted, meaning the declaration is moved to the top of its scope internally by the JavaScript
engine, but only the declaration is hoisted, not the assigned value, so accessing it before the line
it is defined on returns undefined rather than an error. var also allows the same variable to be
redeclared in the same scope without error, which can accidentally overwrite existing values in
larger programs.
2.2 let — Block-Scoped and Reassignable
let was introduced in ES6 to fix the scoping problems of var. A variable declared with let is
block-scoped, meaning it only exists within the nearest enclosing pair of curly braces. It cannot
2
Unit II – JavaScript
be redeclared in the same scope, which helps catch accidental duplicate declarations, but its
value can still be reassigned as many times as needed.
2.3 const — Block-Scoped and Constant
const also creates a block-scoped variable, but it must be assigned a value at the time of
declaration and that value's reference cannot be reassigned afterward. It is important to note that
const only prevents reassignment of the variable itself; if the value is an object or array, the
properties or elements inside it can still be modified, since the reference to the object in memory
does not change.
2.4 Comparison Table
Keywor Scope Re-declare in same Re-assign Hoisting behavior
d scope value
var Function/Global Allowed Allowed Hoisted and initialized
as undefined
let Block Not allowed Allowed Hoisted but not
initialized (temporal
dead zone)
const Block Not allowed Not allowed Hoisted but not
initialized (temporal
dead zone)
2.5 Naming Rules for Variables
• Names can contain letters, digits, underscores, and dollar signs.
• A name must begin with a letter, underscore, or dollar sign; it cannot begin with a digit.
• JavaScript is case-sensitive, so myVar and myvar are treated as two different variables.
• Reserved keywords such as let, var, function, and return cannot be used as variable
names.
Real-Time Example
A shopping cart application uses let for the cart total because the total changes every time an
item is added or removed, while it uses const for fixed values such as the tax rate or the store's
currency symbol, which should never change during the session.
Sample Program: Declaring and Using Variables
<script>
var city = "Chennai"; // function/global scoped, can be re-declared
let age = 21; // block scoped, can be reassigned
const pi = 3.14159; // block scoped, cannot be reassigned
age = 22; // allowed, since age uses let
[Link]("City: " + city);
[Link]("Age: " + age);
[Link]("Value of PI: " + pi);
3
Unit II – JavaScript
// pi = 3.14; // This line would throw: TypeError: Assignment to constant variable.
</script>
3. Data Types
JavaScript is a dynamically (loosely) typed language: a variable's type is decided automatically
at runtime based on the value assigned to it, and the same variable can later hold a value of a
different type. JavaScript data types are divided into primitive types, which hold a single
immutable value, and non-primitive (reference) types, which can hold collections of values or
more complex structures.
3.1 Primitive Data Types
Type Description Example
String Sequence of characters used to represent "Hello World"
text
Number Represents both integers and floating-point 25, 3.14, -10
numbers
Boolean Represents one of two logical values true, false
Undefined Default value of a variable that has been let x;
declared but not assigned
Null Represents the intentional absence of any let y = null;
value
Symbol (ES6) Represents a unique and immutable Symbol('id')
identifier, often used as object keys
BigInt (ES2020) Represents integers larger than the safe 12345678901234567890n
Number limit
3.2 Non-Primitive (Reference) Data Type — Object
Everything that is not a primitive value in JavaScript is an object. Unlike primitives, objects are
stored and copied by reference rather than by value, and they can hold collections of properties
or behaviors.
• Object: A collection of key-value pairs, such as a person's name and age stored together.
• Array: An ordered, list-like object used to store multiple values in a single variable.
• Function: A callable, reusable block of code; in JavaScript, functions are themselves a
special type of object.
4
Unit II – JavaScript
3.3 The typeof Operator
The typeof operator is used to check the data type of a value or variable and returns the type as a
string. One well-known quirk is that typeof null returns "object" rather than "null", which is
considered a long-standing bug retained for backward compatibility.
Real-Time Example
An online registration form uses different data types for different fields: the applicant's name is
stored as a String, their age as a Number, whether they accept the terms and conditions as a
Boolean, and their list of selected hobbies as an Array, all handled automatically by JavaScript's
dynamic typing.
Sample Program: Checking Data Types
<script>
let str = "Hello";
let num = 100;
let bool = true;
let arr = [1, 2, 3];
let obj = { name: "Sam" };
let notAssigned;
let empty = null;
[Link](typeof str); // string
[Link](typeof num); // number
[Link](typeof bool); // boolean
[Link](typeof arr); // object
[Link](typeof obj); // object
[Link](typeof notAssigned); // undefined
[Link](typeof empty); // object (a known JavaScript quirk)
</script>
4. Operators
Operators are special symbols or keywords used to perform operations on operands (variables
and values) to produce a result, such as performing a calculation or comparing two values.
4.1 Arithmetic Operators
Used to perform mathematical calculations: addition, subtraction, multiplication, division,
modulus (remainder), exponentiation, increment, and decrement.
4.2 Assignment Operators
Used to assign values to variables: the basic assignment operator, along with shorthand operators
that combine an arithmetic operation with assignment, such as adding a value directly to an
existing variable.
5
Unit II – JavaScript
4.3 Comparison Operators
Used to compare two values and return a Boolean result: loose equality compares values after
converting types, while strict equality compares both value and type without conversion. Using
strict equality is recommended in modern JavaScript because it avoids unexpected type-
conversion bugs.
4.4 Logical Operators
Used to combine or invert Boolean expressions: AND (true only if both sides are true), OR (true
if at least one side is true), and NOT (inverts a Boolean value).
4.5 Ternary (Conditional) Operator
A shorthand for a simple if-else statement, written in the form condition, then a question mark,
the value if true, a colon, and the value if false.
Real-Time Example
An e-commerce checkout page uses the ternary operator to instantly display 'Free Delivery' or
'Delivery Charges Apply' depending on whether the cart total crosses a minimum amount, and
uses comparison and logical operators together to validate that a discount coupon is both valid
and not expired before applying it.
Sample Program: Using Operators
<script>
let a = 10, b = 3;
[Link]("Sum: " + (a + b)); // 13
[Link]("Modulus: " + (a % b)); // 1
[Link]("a > b: " + (a > b)); // true
[Link]("Equality (==): " + (5 == "5")); // true (type conversion)
[Link]("Strict Equality (===): " + (5 === "5")); // false (no conversion)
let loggedIn = true, hasTicket = false;
[Link]("Can Enter: " + (loggedIn && hasTicket)); // false
[Link]("Can View: " + (loggedIn || hasTicket)); // true
let age = 20;
let canVote = (age >= 18) ? "Eligible" : "Not Eligible";
[Link](canVote); // Eligible
</script>
6
Unit II – JavaScript
5. Functions
A function is a reusable block of code designed to perform a specific task. Instead of writing the
same code repeatedly, a function is defined once and can be called (invoked) as many times as
needed, optionally with different input values.
5.1 Function Declaration
A function declaration uses the function keyword followed by a name, a list of parameters, and a
block of code. Function declarations are hoisted, meaning they can be called even before their
definition appears in the code.
function greet(name) {
return "Hello, " + name + "!";
}
[Link](greet("Anu"));
5.2 Function Expression
A function can also be stored in a variable as a function expression. Unlike function declarations,
function expressions are not hoisted, so they must be defined before they are called.
const greet = function(name) {
return "Hello, " + name + "!";
};
5.3 Parameters, Arguments, and Return Values
• Parameters: The named placeholders listed in a function's definition.
• Arguments: The actual values passed into the function when it is called.
• return statement: Sends a value back to the part of the program that called the function
and immediately ends the function's execution. A function without a return statement
returns undefined.
5.4 Default Parameters
JavaScript allows default values to be specified for parameters, which are used automatically if
no argument is supplied for that parameter.
function greet(name = "Guest") {
return "Hello, " + name;
}
[Link](greet()); // Hello, Guest
[Link](greet("Meena")); // Hello, Meena
Real-Time Example
A billing system in a retail application uses a function such as calculateTotal(price, quantity,
discount) that is called every time a new item is scanned at checkout, returning the final price
after discount, the same function logic is reused for every product instead of being rewritten each
time.
7
Unit II – JavaScript
Sample Program: Function to Calculate Area
<script>
function calculateArea(length, width) {
return length * width;
}
let area = calculateArea(5, 4);
[Link]("Area of rectangle: " + area); // Area of rectangle: 20
</script>
6. DOM Manipulation
The Document Object Model (DOM) is a programming interface that represents an HTML
document as a structured tree of nodes and objects. When a browser loads a web page, it builds
the DOM in memory, and JavaScript can use this model to read, add, change, or remove
elements, attributes, and content dynamically, without needing to reload the page.
6.1 Selecting Elements
Method Description
getElementById(id) Selects a single element that has the specified id
getElementsByClassName(class) Selects all elements that have the specified class,
returned as a collection
getElementsByTagName(tag) Selects all elements with the specified tag name
querySelector(selector) Selects the first element that matches a given CSS
selector
querySelectorAll(selector) Selects all elements that match a given CSS
selector
6.2 Modifying Content and Styles
• innerHTML: Gets or sets the HTML content inside an element, including any nested tags.
• innerText / textContent: Gets or sets only the visible text of an element, without
interpreting HTML tags.
• [Link]: Changes a CSS style directly on an element.
• setAttribute() / getAttribute(): Sets or retrieves the value of an element's attribute, such as
src or href.
6.3 Creating and Removing Elements
• createElement(tag): Creates a new element node that can later be inserted into the page.
• appendChild() / removeChild(): Adds a new child node to an element, or removes an
existing child node from it.
• remove(): Directly removes the element it is called on from the DOM.
8
Unit II – JavaScript
Real-Time Example
A to-do list web application uses DOM manipulation to add a new list item element to the list
every time the user types a task and clicks 'Add', and removes the corresponding list item from
the DOM the moment the user clicks the delete button next to that task, all without refreshing the
page.
Sample Program: Changing Content and Style with the DOM
<!DOCTYPE html>
<html>
<body>
<h2 id="title">Original Title</h2>
<button Text</button>
<script>
function changeContent() {
let heading = [Link]("title");
[Link] = "Title Changed!";
[Link] = "blue";
}
</script>
</body>
</html>
7. Events
An event is an action or occurrence detected by the browser, such as a user clicking a button,
moving the mouse, pressing a key, or a page finishing its load. JavaScript can listen for these
events using event handlers and execute a function in response, which is what makes web pages
interactive rather than purely static.
7.1 Common Events
Event Triggered When
click An element is clicked by the user
mouseover / mouseout The mouse pointer enters or leaves an element
keydown / keyup A keyboard key is pressed down or released
submit A form is submitted
load A page or resource finishes loading
change The value of an input, select, or textarea element changes
focus / blur An element gains or loses keyboard/input focus
9
Unit II – JavaScript
7.2 Ways to Handle Events
• Inline HTML attribute: an onclick attribute placed directly on the element. Quick but
mixes JavaScript with HTML, which is not ideal for larger projects.
• DOM property assignment: assigning a function directly to an element's onclick property
in JavaScript.
• addEventListener(): the recommended modern approach, since it allows multiple listeners
on the same event and keeps structure (HTML) separate from behavior (JavaScript).
7.3 The Event Object
When an event occurs, the browser automatically passes an event object to the handler function,
which contains useful details about the event, such as which element triggered it and which key
was pressed for keyboard events.
Real-Time Example
A login form uses the submit event together with addEventListener to validate the username and
password fields before the form data is actually sent to the server, and uses the keyup event on
the password field to show a live strength indicator as the user types.
Sample Program: Handling a Button Click Event
<!DOCTYPE html>
<html>
<body>
<button id="myBtn">Click Me</button>
<p id="output"></p>
<script>
[Link]("myBtn").addEventListener("click", function() {
[Link]("output").innerHTML = "Button was clicked!";
});
</script>
</body>
</html>
8. ES6 Features
ECMAScript 6 (ES6), released in 2015, is one of the most significant updates to JavaScript. It
introduced syntax and features that made the language more concise, readable, and easier to
maintain, including arrow functions, the let and const keywords, and template literals.
8.1 Arrow Functions
Arrow functions, introduced in ES6, provide a shorter syntax for writing function expressions
using the arrow symbol. If the function body is a single expression, the curly braces and the
return keyword can be omitted, and the expression's value is returned automatically. Arrow
functions also do not have their own 'this' binding, they inherit 'this' from their surrounding
(enclosing) scope, which avoids common bugs when using 'this' inside callbacks.
10
Unit II – JavaScript
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function (equivalent)
const add = (a, b) => a + b;
// Arrow function with one parameter (parentheses optional)
const square = x => x * x;
8.2 let and const
As discussed earlier, let and const were introduced in ES6 to provide block-level scoping in
place of the function-scoped and hoisting-prone var keyword. The general best practice in
modern JavaScript is to use const by default, and switch to let only when a variable's value
genuinely needs to change.
let count = 1; // can be reassigned later
const maxLimit = 100; // value is fixed and cannot be reassigned
8.3 Template Literals
Template literals use backtick characters instead of single or double quotes. They allow string
interpolation, embedding variables or expressions directly inside a string, and they also support
multi-line strings without needing special characters such as a newline escape.
let name = "Riya";
let age = 21;
// Old way (string concatenation)
let oldMsg = "My name is " + name + " and I am " + age + " years old.";
// Template literal (ES6)
let message = `My name is ${name} and I am ${age} years old.`;
[Link](message);
Real-Time Example
A weather application uses a template literal to build the displayed forecast text, automatically
inserting live values such as city name, temperature, and condition fetched from a weather API,
and uses arrow functions to handle the click events on each forecast card.
Sample Program: Using ES6 Features Together
<script>
const greetUser = (name, age) => {
return `Hello ${name}, you are ${age} years old.`;
};
let user = "Karthik";
const userAge = 23;
11
Unit II – JavaScript
[Link](greetUser(user, userAge));
</script>
9. Promises
A Promise is a JavaScript object that represents the eventual completion (or failure) of an
asynchronous operation, such as fetching data from a server. Before Promises were introduced,
asynchronous code relied heavily on nested callback functions, which often became difficult to
read and maintain, commonly called 'callback hell'. Promises provide a cleaner, chainable way to
handle the result of an asynchronous task once it is available.
9.1 States of a Promise
• Pending: The initial state, the asynchronous operation has started but has not yet
completed.
• Fulfilled: The operation completed successfully, and the resolve function was called with
a result value.
• Rejected: The operation failed, and the reject function was called with an error or reason.
Once a Promise becomes fulfilled or rejected, it is said to be settled, and its state cannot change
again.
9.2 Creating a Promise
A Promise is created using the Promise constructor, which takes a function (called the executor)
with two parameters: resolve and reject. Inside this function, resolve is called when the task
succeeds, and reject is called when it fails.
9.3 Consuming a Promise
• .then(): Registers a callback to run when the Promise is fulfilled, receiving the resolved
value as its argument.
• .catch(): Registers a callback to run when the Promise is rejected, receiving the
error/reason as its argument.
• .finally(): Registers a callback that runs once the Promise is settled, regardless of whether
it was fulfilled or rejected, commonly used to stop a loading indicator.
Real-Time Example
When a user clicks 'Pay Now' on an online payment page, the request to the payment gateway is
handled as a Promise: the page shows a loading spinner while the Promise is pending, displays a
success message in then() if the payment is approved, and shows an error message in catch() if
the payment fails or the gateway times out.
Sample Program: Creating and Using a Promise
<script>
function checkEvenNumber(num) {
return new Promise((resolve, reject) => {
if (num % 2 === 0) {
resolve(num + " is even");
12
Unit II – JavaScript
} else {
reject(num + " is odd");
}
});
}
checkEvenNumber(10)
.then(result => [Link]("Success: " + result))
.catch(error => [Link]("Error: " + error))
.finally(() => [Link]("Check complete."));
</script>
10. Async/Await
async and await are keywords introduced in ES2017 (ES8) that are built on top of Promises.
They allow asynchronous code to be written in a way that looks and reads like ordinary,
synchronous, step-by-step code, which makes it significantly easier to understand and debug
compared to long chains of then() calls.
10.1 The async Keyword
Placing the async keyword before a function declaration marks it as an asynchronous function.
An async function always returns a Promise automatically, even if the function's body returns a
plain value, JavaScript wraps it in a resolved Promise.
10.2 The await Keyword
The await keyword can only be used inside an async function. When placed before a Promise, it
pauses the execution of that async function until the Promise settles, and then returns the
resolved value directly, without needing a then() callback. If the Promise is rejected, await
throws the rejection as an error, which can then be caught.
10.3 Error Handling with try...catch
Since await can throw an error when a Promise is rejected, async functions typically wrap
awaited calls in a try...catch block, which provides a clean, readable way to handle errors, similar
to how catch() is used in a then() chain.
Real-Time Example
A social media feed loads posts using an async function: it shows a loading skeleton, then uses
await to pause until the server responds with the user's posts, displays them once they arrive, and
uses a try...catch block to show 'Unable to load feed' if the network request fails, all while the
rest of the page remains responsive.
Sample Program: Fetching Data Using Async/Await
<script>
function fetchUserData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: "Priya", age: 22 });
13
Unit II – JavaScript
}, 1000);
});
}
async function displayUser() {
try {
[Link]("Fetching user data...");
let user = await fetchUserData();
[Link](`Name: ${[Link]}, Age: ${[Link]}`);
} catch (error) {
[Link]("Error fetching data: " + error);
}
}
displayUser();
</script>
14