0% found this document useful (0 votes)
282 views26 pages

Dynamic HTML: DOM & JavaScript Basics

wd

Uploaded by

ssascw.bca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
282 views26 pages

Dynamic HTML: DOM & JavaScript Basics

wd

Uploaded by

ssascw.bca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SEMESTER III

UNIT IV: Dynamic HTML Hours:6


Document object model (DCOM)-Accessing HTML & CSS through DCOM Dynamic
content styles & positioning-Event bubbling-data binding. JavaScript: Client-side scripting,
What is JavaScript, How to develop JavaScript, simple JavaScript, variables, functions,
conditions, loops and repetition.
Document object model (DCOM)
"Document Object Model" (DOM) refers to a programming interface that allows developers
to access and manipulate the structure, content, and style of an HTML document dynamically
using JavaScript, essentially enabling interactive and changing elements on a web page
without needing to reload the entire page; it essentially represents the HTML document as a
tree-like structure with nodes that can be accessed and modified.
Key points about DOM in DHTML:
Structure:
The DOM presents an HTML document as a hierarchical tree where each element
(like <p>, <div>, etc.) is a node, allowing you to navigate and interact with specific parts of
the page.
Manipulation:
Using JavaScript, you can add, remove, modify, or change the attributes of DOM nodes to
dynamically update the content on the page.
Example Use Cases:
Changing the text content of a paragraph based on user input
Adding new elements to a page when a button is clicked
Animating elements by adjusting their position or style over time

Imagine your webpage as a tree


 The document is the root.
 HTML tags like <html>, <head>, and <body> are branches.
 Attributes, text, and other elements are the leaves.

The DOM is essential because


 Dynamic Content Updates: Without reloading the page, the DOM allows content
updates (e.g., form validation, AJAX responses).
 User Interaction: It makes your webpage interactive (e.g., responding to button clicks,
form submissions).
 Flexibility: Developers can add, modify, or remove elements and styles in real-time.
 Cross-Platform Compatibility: It provides a standard way for scripts to interact with
web documents, ensuring browser compatibility.

How the DOM Works?


The DOM connects your webpage to JavaScript, allowing you to:
 Access elements (like finding an <h1> tag).
 Modify content (like changing the text of a <p> tag).

Prof. [Link] [Link].,[Link].,BEd., Page 1


 React to events (like a button click).
 Create or remove elements dynamically.
Properties of the DOM
 Node-Based: Everything in the DOM is represented as a node (e.g., element nodes, text
nodes, attribute nodes).
 Hierarchical: The DOM has a parent-child relationship, forming a tree structure.
 Live: Changes made to the DOM using JavaScript are immediately reflected on the web
page.
 Platform-Independent: It works across different platforms, browsers, and
programming languages.
Key Concepts:

1. Structure Representation: The DOM provides a tree-like structure where each part
of a webpage (such as elements, attributes, and text) is represented as nodes. This
makes it possible to access and modify elements like HTML tags, attributes, and text
content.
2. Manipulation: Using JavaScript, the DOM allows you to:
o Add, remove, or modify elements (like <div>, <span>, etc.).
o Change styles (using inline CSS or through style properties).
o Handle events (like onclick, onmouseover).

3. Dynamic Content: The "dynamic" part of DHTML refers to the ability to change
content without reloading the entire page. With JavaScript and the DOM, you can
modify the webpage in real-time, making it interactive and responsive.

Example:

Imagine you have an HTML document:

html
CopyEdit
<!DOCTYPE html>
<html>
<head>
<title>DHTML DOM Example</title>
<style>
#myText {
color: blue;
}
</style>
</head>
<body>
<h1>Welcome to DHTML!</h1>
<p id="myText">This text is blue.</p>
<button onclick="changeText()">Click me</button>

<script>
function changeText() {
var element = [Link]("myText");

Prof. [Link] [Link].,[Link].,BEd., Page 2


[Link] = "The text has changed!";
[Link] = "red"; // Changing the text color dynamically
}
</script>
</body>
</html>
Explanation:

 [Link]("myText"): This gets the HTML element with the ID


myText (the paragraph <p>).
 [Link] = "The text has changed!": Changes the text content of the
paragraph.
 [Link] = "red": Dynamically changes the text color to red.

The DOM allows the page to be altered in response to events like button clicks, making it a
core part of DHTML for creating interactive and dynamic web pages.

Attach
Search
Reason

Accessing HTML & CSS through DCOM Dynamic content styles & positioning

Dynamic content system that involves HTML and CSS, possibly related to dynamic content
or elements in a web application, and managing styles and positioning dynamically.

Dynamic content styles and positioning, there are several concepts and tools you might be
referring to. Below is an overview of how HTML and CSS work in dynamic content systems,
with focus on DCOM (Dynamic Component Object Model) if that's part of your scenario.

1. Dynamic Content in HTML & CSS:

Dynamic content refers to content on a webpage that can change or update without the user
manually refreshing the page. This could include things like live updates, interactive forms,
or content that changes based on user input or data from the server.

Prof. [Link] [Link].,[Link].,BEd., Page 3


Example use cases:

 AJAX (Asynchronous JavaScript and XML): Allows dynamic updates by fetching


new data from the server without reloading the entire page.
 CSS Transitions/Animations: For changing styles (e.g., hover effects, sliding
menus) dynamically.
 JavaScript: Can be used to modify the DOM (Document Object Model) dynamically,
adding, removing, or changing HTML elements and their associated styles.

2. Positioning in CSS:

CSS positioning allows you to control the layout of elements on a page dynamically. There
are several key positioning methods:

 Static: The default positioning method. Elements are placed in the normal document
flow.
 Relative: Elements are positioned relative to their normal position in the document
flow.
 Absolute: Elements are positioned relative to their closest positioned ancestor or the
initial containing block.
 Fixed: Elements are positioned relative to the viewport, so they stay in place even
when the page is scrolled.
 Sticky: A hybrid of relative and fixed positioning. The element is treated as relative
until it crosses a specific point in the viewport, after which it becomes fixed.

3. DCOM (Dynamic Component Object Model):

DCOM is typically associated with Windows and is used for communication between
software components over a network. However, in the context of web development, it's likely
you're referring to dynamic components (like a CMS, JavaScript-driven components, or
dynamic front-end frameworks) rather than DCOM itself. If you're using JavaScript
frameworks (React, Vue, Angular) or libraries that allow dynamic content generation and
style changes, CSS properties such as display, position, and transform can be manipulated.

Prof. [Link] [Link].,[Link].,BEd., Page 4


Example with JavaScript (React, Vue, or Vanilla JS):

// Changing element's style dynamically using JavaScript


[Link]('myElement').[Link] = 'absolute';
[Link]('myElement').[Link] = '50px';
[Link]('myElement').[Link] = '100px';

In frameworks like React, you may use inline styles with style={{}} or dynamic class names
to change styles based on the state of a component.

4. Dynamic Positioning with JavaScript (Example):

Here's an example of dynamically changing the position of an element based on user


interaction:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.dynamic-box {
width: 100px;
height: 100px;
background-color: blue;
position: absolute; /* This enables positioning */
top: 0;
left: 0;
transition: top 0.5s, left 0.5s; /* Smooth transition for position */
}
</style>
<title>Dynamic Positioning</title>
</head>

Prof. [Link] [Link].,[Link].,BEd., Page 5


<body>
<div id="box" class="dynamic-box"></div>

<button id="moveButton">Move Box</button>


<script>
const box = [Link]('box');
const button = [Link]('moveButton');
[Link]('click', function() {
// Randomize new position within the window's dimensions
const newTop = [Link]() * [Link];
const newLeft = [Link]() * [Link];
// Change the position of the box dynamically
[Link] = `${newTop}px`;
[Link] = `${newLeft}px`;
});
</script>
</body>
</html>

In this example:

 A blue box is positioned absolutely on the page.


 When the user clicks the "Move Box" button, the position of the box is updated
dynamically using JavaScript, creating a random position each time.

5. Considerations for Dynamic Content & Positioning:

 Responsiveness: When dealing with dynamic content and positioning, ensure your
layout adapts to different screen sizes. This might involve using CSS media queries or
flexible layout systems like Flexbox or Grid.
 Performance: Excessive DOM manipulations or complex animations may negatively
impact performance, especially for mobile users. Consider using
requestAnimationFrame for smoother animations or reducing layout reflows and
repaints.

Prof. [Link] [Link].,[Link].,BEd., Page 6


Event bubbling

Event bubbling is a concept in DHTML (Dynamic HTML) that describes how events
propagate through the DOM (Document Object Model) hierarchy. It refers to the order in
which events are handled by elements in the DOM when an event (such as a mouse click,
key press, etc.) occurs.

How Event Bubbling Works:

1. Event Triggered: An event (like a click) is triggered on a specific element (for


example, a button).
2. Propagation: The event bubbles up from the target element to the root of the
document. It first goes to the target element (where it originated), then to its parent,
then its parent’s parent, and so on, until it reaches the <html> element.
3. Event Listeners: As the event propagates up the DOM, any parent elements that have
an event listener for the same type of event can handle it. This is where you can attach
listeners at various levels (child or parent).
4. Stopping the Bubbling: You can prevent further propagation of the event by using
the [Link]() method. This stops the event from bubbling up to parent
elements.

Example:

Imagine a webpage with nested HTML elements, such as a div containing a button:

<div id="parent">
<button id="child">Click me!</button>
</div>

If you attach event listeners to both the button (child) and the div (parent):

[Link]("child").addEventListener("click", function(event)
{
alert("Button clicked");
});
[Link]("parent").addEventListener("click", function(event)
{
alert("Div clicked");
});

Prof. [Link] [Link].,[Link].,BEd., Page 7


When you click the button, you will first see the Button clicked alert (because the event is
first captured on the button). Then, the event will bubble up to the parent div, triggering the
Div clicked alert.

Event Bubbling Flow:

 Click on the button:


1. button element triggers the click event.
2. Event bubbles up to the div element, and its event listener is triggered.

Stopping the Bubble:

If you want to prevent the event from reaching the parent elements, you can stop the event
from bubbling:

javascript
[Link]("child").addEventListener("click", function(event) {
alert("Button clicked");
[Link](); // Prevent the event from bubbling up
});

With [Link](), only the button's event listener is executed, and the parent div
won't receive the event.

Key Points:

 Event Bubbling: The event starts at the target and propagates up the DOM.
 [Link](): Stops the event from propagating to parent elements.
 Use Case: Event delegation can be achieved using event bubbling, allowing you to
attach a single event listener to a parent element instead of multiple listeners on many
child elements.

Data binding

Data binding in DHTML (Dynamic HTML) refers to the concept of connecting data to
HTML elements dynamically, so that the content on the web page updates automatically
when the underlying data changes. In the context of DHTML, data binding involves
connecting JavaScript code with HTML elements (like text boxes, tables, etc.) so that the
DOM (Document Object Model) can reflect any changes in the data without needing to
refresh the page.

Basic Data Binding in DHTML

1. JavaScript and DOM Manipulation: You can manipulate the DOM using
JavaScript to bind data to elements on the page. When the data changes, JavaScript
will update the HTML elements.
2. Example of Simple Binding:

Prof. [Link] [Link].,[Link].,BEd., Page 8


Suppose you have a simple web page where you want to display a user’s name:

<!DOCTYPE html>
<html>
<head>
<title>Data Binding Example</title>
</head>
<body>
<div>
<p>Name: <span id="userName"></span></p>
<button onclick="updateName()">Change Name</button>
</div>

<script>
let user = { name: 'John Doe' };

// Function to bind data


function bindData() {
[Link]('userName').textContent = [Link];
}
// Function to update the name and re-bind data
function updateName() {
[Link] = 'Jane Smith';
bindData();
}
// Initial data binding
bindData();
</script>
</body>
</html>

In this example:

o The bindData() function is responsible for updating the content of the span
element (#userName) with the value from the JavaScript [Link].
o The updateName() function changes the [Link] and then calls bindData()
again to update the page.

Two-Way Data Binding

A more complex concept would be two-way data binding, where changes to the HTML
elements reflect in the data model and vice versa. For this, you often need more advanced
JavaScript code or frameworks. One simple example using plain JavaScript could be using
event listeners:

<!DOCTYPE html>
<html>
<head>
<title>Two-Way Data Binding Example</title>
</head>

Prof. [Link] [Link].,[Link].,BEd., Page 9


<body>
<div>
<input type="text" id="inputName" />
<p>Your name is: <span id="displayName"></span></p>
</div>

<script>
let user = { name: '' };

// Function to bind data to the UI


function bindData() {
[Link]('displayName').textContent = [Link];
[Link]('inputName').value = [Link];
}

// Function to update the data when input changes


[Link]('inputName').addEventListener('input', function(event) {
[Link] = [Link];
bindData();
});
// Initial binding
bindData();
</script>
</body>
</html>

In this case:

 The input field is bound to [Link].


 Whenever the user types in the input field, the input event updates the [Link]
property, and the display is updated accordingly.

DHTML Frameworks for Data Binding

There are also many JavaScript libraries and frameworks that offer more advanced data
binding capabilities, such as:

 AngularJS (for two-way data binding)


 React (uses a one-way data flow, but can be managed to look like data binding)
 [Link] (simple and efficient two-way data binding)

While these modern frameworks make data binding easier and more powerful, you can still
implement basic data binding in pure JavaScript like the examples above.

Prof. [Link] [Link].,[Link].,BEd., Page 10


What is Javascript?

JavaScript is a versatile, dynamically typed programming language used for interactive web
applications, supporting both client-side and server-side development, and integrating
seamlessly with HTML, CSS, and a rich standard library.
 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 that’s why it is
called dynamically typed.
“Hello, World!” Program in Browser Console
A “Hello, World!” program is the simplest way to get started with any programming
language. Here’s how you can write one using JavaScript.
<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>
In this example
 The<script> tag is used to include JavaScript code inside an HTML document.
 [Link]() prints messages to the browser’s developer console. Open the browser
console to see the “Hello, World!” message.
“Hello World” Program in Server Console
We can also print the “Hello World” program directly into the console terminal without
embedded it into HTML. Create an [Link] file and add the code to it.
/*
This is a multi-line comment.
It can span several lines.
*/
[Link]("Hello, World!"); // Prints Hello, World! to the console

Prof. [Link] [Link].,[Link].,BEd., Page 11


In this example
 [Link](): The [Link]() method is used to print messages to the browser’s
developer console. Open the console (usually with F12 or Ctrl + Shift + J) to see the
message “Hello, World!” displayed.
 Comments in the Code:
o Multi-line Comment: The /* */ syntax is used to write a comment spanning
multiple lines.
o Single-line Comment: The // syntax is used for short, inline comments, like
the one explaining the [Link] function.
Features of JavaScript
 Client-Side Scripting:JavaScript runs on the user’s browser, so has a faster response
time without needing to communicate with the server.
 Versatile: JavaScript can be used for a wide range of tasks, from simple calculations to
complex server-side applications.
 Event-Driven: JavaScript can respond to user actions (clicks, keystrokes) in real-time.
 Asynchronous: JavaScript 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.
Client Side and Server Side nature of JavaScript
 Client-side: Involves controlling the browser and its DOM, handling user events like
clicks and form inputs. Libraries such as AngularJS, ReactJS, and VueJS are commonly
used.
 Server-side: Involves interacting with databases, manipulating files, and generating
responses. With [Link] and frameworks like [Link], JavaScript is also widely used
on the server side.
 Imperative Programming: Focuses on how to perform tasks, controlling the flow of
computation. It includes approaches like procedural and object-oriented programming,
often using constructs like async/await to handle actions.
 Declarative Programming: Focuses on what should be done rather than how it’s done.
It emphasizes describing the desired result, like with arrow functions, without detailing
the steps to achieve it.

Prof. [Link] [Link].,[Link].,BEd., Page 12


Applications of JavaScript
 Web Development: JavaScript adds interactivity and dynamic behavior to static
websites, with popular frameworks like AngularJS enhancing development.
 Web Applications: JavaScript powers robust web applications,
leveraging APIs, React, and Electron to create dynamic user experiences like Google
Maps.
 Server Applications: [Link] brings JavaScript to the server side, enabling powerful
server applications and full-stack development.
 Game Development: JavaScript, combined with HTML5 and libraries like Ease JS,
enables the creation of interactive games for the web.
 Smartwatches: Pebble JS allows JavaScript to run on smartwatches, supporting apps
that require internet connectivity.

How to develop Javascript

Developing JavaScript involves writing and running code that adds interactivity and
functionality to web pages. Here's a step-by-step guide to help you get started with JavaScript
development:

1. Set Up Your Environment

To develop JavaScript, you need a few basic tools:

 A Text Editor: You can use any text editor to write JavaScript. Popular options
include:
o VSCode (Visual Studio Code): Highly recommended for web development
with great extensions for JavaScript.
o Sublime Text: A lightweight editor with JavaScript syntax support.
o Atom: A customizable open-source editor.
o Notepad++: A simple text editor for Windows users.

 Web Browser: You'll need a browser to run and test your JavaScript. Most modern
browsers (Chrome, Firefox, Edge) have built-in developer tools to help debug
JavaScript code.

Variables

Global Variables
Global variables in JavaScript are those declared outside of any function or block scope.
They are accessible from anywhere within the script, including inside functions and blocks.
Variables declared without the var, let, or const keywords (prior to ES6) inside a function
automatically become global variables.

Prof. [Link] [Link].,[Link].,BEd., Page 13


However, variables declared with var, let, or const inside a function are local to that
function unless explicitly marked as global using window (in browser environments)
or global (in [Link]).
Characteristics of Global Variables:
 Scope: Accessible throughout the entire script, including inside functions and blocks.
 Automatic Global Variables: If a variable is declared inside a function without var,
let, or const, it automatically becomes a global variable (a common source of bugs).

Local Variables
Local variables are defined within functions in JavaScript. They are confined to the scope
of the function that defines them and cannot be accessed from outside. Attempting to access
local variables outside their defining function results in an error.
Characteristics of Local Variables:
 Scope: Limited to the function or block in which they are declared.
 Function-Specific: Each function can have its own local variables, even if they share
the same name
Variables
A variable is like a container that holds data that can be reused or updated later in the
program. In JavaScript, variables are declared using the keywords var, let, or const.
1. var Keyword
The var keyword is used to declare a variable. It has a function-scoped or globally-scoped
behaviour.
Example
var n = 5;
[Link](n);
var n = 20; // reassigning is allowed
[Link](n);

output

5
20
2. let Keyword
The let keyword is introduced in ES6, has block scope and cannot be re-declared in the
same scope.
Example
let n= 10;

Prof. [Link] [Link].,[Link].,BEd., Page 14


n = 20; // Value can be updated
// let n = 15; //can not redeclare
[Link](n)

Output
20
3. const Keyword
The const keyword declares variables that cannot be reassigned. It’s block-scoped as well.
Example
const n = 100;
// n = 200; This will throw an error
[Link](n)

Output
100
Data Types
JavaScript supports various datatypes, which can be broadly categorized into primitive and
non-primitive types.
Primitive Datatypes
Primitive datatypes represent single values and are immutable.
1. Number: Represents numeric values (integers and decimals).
let n = 42;
let pi = 3.14;
2. String: Represents text enclosed in single or double quotes.
let s = "Hello, World!";
3. Boolean: Represents a logical value (true or false).
let bool= true;
[Link]: A variable that has been declared but not assigned a value.
Example
let notAssigned;
[Link](notAssigned);
output
undefined

5. Null: Represents an intentional absence of any value.


let empty = null;
6. Symbol: Represents unique and immutable values, often used as object keys.
let sym = Symbol('unique');
7. BigInt: Represents integers larger than Number.MAX_SAFE_INTEGER.
let bigNumber = 123456789012345678901234567890n;

Prof. [Link] [Link].,[Link].,BEd., Page 15


Non-Primitive Datatypes
Non-primitive types are objects and can store collections of data or more complex entities.
[Link]: Represents key-value pairs.
 let obj = {
name: "Amit",
age: 25
};

2. Array: Represents an ordered list of values.


let a = ["red", "green", "blue"];

3. Function: Represents reusable blocks of code.


function fun() {
[Link]("GeeksforGeeks");
}

Functions in JavaScript

Functions in JavaScript are reusable blocks of code designed to perform specific tasks.
They allow you to organize, reuse, and modularize code. It can take inputs, perform actions,
and return outputs.

Function Definition
A Function Definition or function statement starts with the function keyword and
continues with the following.
 Function’s name.
 A list of function arguments contained in parenthesis and separated by commas.
 Statements are enclosed in curly brackets.
Syntax:
function name(arguments)
{
javascript statements
}

Example

function sum(x, y) {
return x + y;
}
[Link](sum(6, 9));

Output
15
Function Syntax and Working
A function definition is sometimes also termed a function declaration or function statement.
Below are the rules for creating a function in JavaScript:

Prof. [Link] [Link].,[Link].,BEd., Page 16


 Begin with the keyword function followed by,
 A user-defined function name (In the above example, the name is sum)
 A list of parameters enclosed within parentheses and separated by commas (In the
above example, parameters are x and y)
 A list of statements composing the body of the function enclosed within curly braces {}
(In the above example, the statement is “return x + y”).
Return Statement
In some situations, we want to return some values from a function after performing some
operations. In such cases, we make use of the return. This is an optional statement. In the
above function, “sum()” returns the sum of two as a result.
Function Parameters
Parameters are input passed to a function. In the above example, sum() takes two
parameters, x and y.
Calling Functions
After defining a function, the next step is to call them to make use of the function. We can
call a function by using the function name separated by the value of parameters enclosed
between the parenthesis.
// Function Definition
function welcomeMsg(name) {
return ("Hello " + name + " welcome to GeeksforGeeks");
}

let nameVal = "User";

// calling the function


[Link](welcomeMsg(nameVal));

Output
Hello User welcome to GeeksforGeeks

Why Functions?
 Functions can be used multiple times, reducing redundancy.
 Break down complex problems into manageable pieces.
 Manage complexity by hiding implementation details.
 Can call themselves to solve problems recursively.
Function Invocation
The function code you have written will be executed whenever it is called.
 Triggered by an event (e.g., a button click by a user).
 When explicitly called from JavaScript code.
 Automatically executed, such as in self-invoking functions.
Function Expression
It is similar to a function declaration without the function name. Function expressions can be
stored in a variable assignment.
Syntax:
let geeksforGeeks= function(paramA, paramB) {
// Set of statements
}
Example:
const mul = function (x, y) {

Prof. [Link] [Link].,[Link].,BEd., Page 17


return x * y;
};
[Link](mul(4, 5));

Output
20
Arrow Functions
Arrow functions are a concise syntax for writing functions, introduced in ES6, and they do
not bind their own this context.
Syntax:
let function_name = (argument1, argument2 ,..) => expression

Example:
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = [Link](function (s) {


return [Link];
});

[Link]("Normal way ", a2);

const a3 = [Link]((s) => [Link]);

[Link]("Using Arrow Function ", a3);

Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
Immediately Invoked Function Expression (IIFE)
IIFE functions are executed immediately after their definition. They are often used to create
isolated scopes.

(function () {

[Link]("This runs immediately!");

})();

Output
This runs immediately!
Callback Functions
A callback function is passed as an argument to another function and is executed after the
completion of that function.

Example
function num(n, callback) {
return callback(n);
}

Prof. [Link] [Link].,[Link].,BEd., Page 18


const double = (n) => n * 2;

[Link](num(5, double));

Output
10
Anonymous Functions
Anonymous functions are functions without a name. They are often used as arguments to
other functions.
setTimeout(function () {
[Link]("Anonymous function executed!");
}, 1000);
function outerFun(a) {
function innerFun(b) {
return a + b;
}
return innerFun;
}

const addTen = outerFun(10);


[Link](addTen(5));

Output
15
Pure Functions
Pure functions return the same output for the same inputs and do not produce side effects.
They do not modify state outside their scope, such as modifying global variables, changing
the state of objects passed as arguments, or performing I/O operations.
function pureAdd(a, b) {
return a + b;
}

[Link](pureAdd(2, 3));

Output
5

Characteristics of Functions
 Parameters and Arguments: Functions can accept parameters (placeholders) and be
called with arguments (values).
 Return Values: Functions can return a value using the return keyword.
 Default Parameters: Default values can be assigned to function parameters.
Advantages of Functions in JavaScript
 Reusability: Write code once and use it multiple times.

Prof. [Link] [Link].,[Link].,BEd., Page 19


 Modularity: Break complex problems into smaller, manageable pieces.
 Improved Readability: Functions make code easier to understand.
 Maintainability: Changes can be made in one place without affecting the entire
codebase.
JavaScript Loops

Loops in JavaScript are used to reduce repetitive tasks by repeatedly executing a block of
code as long as a specified condition is true. This makes code more concise and efficient.

Suppose we want to print ‘Hello World’ five times. Instead of manually writing the print
statement repeatedly, we can use a loop to automate the task and execute it based on the
given condition.

for (let i = 0; i < 5; i++) {


[Link]("Hello World!");
}
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

Types
1)for loop when the number of iterations is known.
2)while loop when the condition depends on dynamic factors.
3)do-while loop to ensure the block executes at least once.
4)for…in loop to iterate over object properties.
5)for…of loop for iterating through iterable objects.

1. JavaScript for Loop


The for loop repeats a block of code a specific number of times. It contains initialization,
condition, and increment/decrement in one line.
Syntax
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example
for (let i = 1; i <= 3; i++) {

Prof. [Link] [Link].,[Link].,BEd., Page 20


[Link]("Count:", i);
}

Output
Count: 1
Count: 2
Count: 3
In this example
 Initializes the counter variable (let i = 1).
 Tests the condition (i <= 3); runs while true.
 Executes the loop body and increments the counter (i++).
2. JavaScript while Loop
The while loop executes as long as the condition is true. It can be thought of as a repeating
if statement.
Syntax
while(condition)
{
//Codetoexecute
}
let i = 0;
while (i < 3) {
[Link]("Number:", i);
i++;
}

Output
Number: 0
Number: 1
Number: 2
In this example
 Initializes the variable (let i = 0).
 Runs the loop body while the condition (i < 3) is true.
 Increments the counter after each iteration (i++).
3. JavaScript do-while Loop
The do-while loop is similar to while loop except it executes the code block at least once
before checking the condition.
Syntax
do
{
//Codetoexecute
} while (condition);
Example
let i = 0;
do {
[Link]("Iteration:", i);
i++;
} while (i < 3);

Prof. [Link] [Link].,[Link].,BEd., Page 21


Output
Iteration: 0
Iteration: 1
Iteration: 2
In this example:
 Executes the code block first.
 Checks the condition (i < 3) after each iteration.
4. JavaScript for-in Loop
The for…in loop is used to iterate over the properties of an object. It only iterate over keys
of an object which have their enumerable property set to “true”.
Syntax
for(letkey in object)
{
//Codetoexecute
}
const obj = { name: "Ashish", age: 25 };
for (let key in obj) {
[Link](key, ":", obj[key]);
}

Output
name : Ashish
age : 25
In this example:
 Iterates over the keys of the person object.
 Accesses both keys and values.
5. JavaScript for-of Loop
The for…of loop is used to iterate over iterable objects like arrays, strings, or sets. It
directly iterate the value and has more concise syntax than for loop.
Syntax
for(letvalueofiterable)
{
//Codetoexecute
}

Example:
let a = [1, 2, 3, 4, 5];
for (let val of a) {
[Link](val);
}

Output
1
2
3

Prof. [Link] [Link].,[Link].,BEd., Page 22


4
5

Conditional Statements
JavaScript have the following conditional statements:

i)if to specify a block of code to be executed, if a specified condition is true

ii)else to specify a block of code to be executed, if the same condition is false

iii)else if to specify a new condition to test, if the first condition is false

iv)switch to specify many alternative blocks of code to be executed

i)The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

The if statement is used to evaluate a particular condition. If the condition holds true, the
associated code block is executed.

Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
Example
<script>
let i = 10;
if (i > 15) [Link]("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
[Link]("I am Not in if");
</script>
Output
I am Not in if
The if else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

The if-else statement will perform some action for a specific condition. Here we are using
the else statement in which the else statement is written after the if statement and it has no
condition in their code block .

Prof. [Link] [Link].,[Link].,BEd., Page 23


if (condition)
{
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
<script>
let i = 10;

if (i < 15)
[Link]("i is less than 15");
else
[Link]("I am Not in if");
</script>

Output
i is less than 15
The JavaScript Switch Statement

Use the switch statement to select one of many code blocks to be executed.

As the number of conditions increases, you can use multiple else-if statements in
JavaScript. but when we dealing with many conditions, the switch statement may be a more
preferred option.

Syntax
switch(expression)
{
case x:
//codeblock
break;
case y:
//codeblock
break;
default:
// codeblock
}

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 If there is no match, the default code block is executed.

Switch Statement Example: Here, we will print the day name on day 3.

Prof. [Link] [Link].,[Link].,BEd., Page 24


The getDay() method returns the weekday as a number between 0 and 6.

(Sunday=0, Monday=1, Tuesday=2 ..)

Example:
let day = 3;
let dayName;

switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}

[Link](dayName); // Output: Wednesday

Output
Wednesday
Explanation:
 Day is set to 3.
 The switch statement evaluates day.
 Since day is 3, the case 3 the block is executed, assigning "Wednesday" to dayName.
 The break statement ends the switch statement, preventing execution from continuing
into other cases.

continue statement
continue statement in JavaScript is used to break the iteration of the loop and follow with
the next iteration.
 Example of continue to print only odd Numbers smaller than 10
 for (let i = 0; i < 10; i++) {

Prof. [Link] [Link].,[Link].,BEd., Page 25


 if (i % 2 == 0) continue;
 [Link](i);
 }

Output
 1
 3
 5
 7
 9

JavaScript break statement


JavaScript break statement is used to terminate the execution of the loop or the switch
statement when the condition is true.
In a For Loop (To come out of the Loop)
Example
for (let i = 1; i < 6; i++) {
if (i == 4) break;
[Link](i);
}
Output
1
2
3
return statement
The return statement in JavaScript is used to end the execution of a function and return a
value to the caller. It is used to control function behaviour and optimise code execution.
Syntax
return [expression]
 Expression Evaluation: The expression inside the brackets is evaluated and returned to
the caller.
 List of Results: When returning multiple values, arrays or objects can be used to
structure the data.
 Example:
 function add(a, b) {
 return a + b;
 }
 const res = add(5, 10);
 [Link](res);

 Output
 15

Prof. [Link] [Link].,[Link].,BEd., Page 26

You might also like