[Go to site: main page, start]

0% found this document useful (0 votes)
6 views43 pages

Understanding Markup, Styling, and Scripting Languages

Uploaded by

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

Understanding Markup, Styling, and Scripting Languages

Uploaded by

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

Unit – 4

1. Markup Language:

A markup language is used to structure and describe the content of a web page or document.
It does not perform any logic or calculation — it only defines what elements are present and
how they are organized.

Purpose:

To describe the layout and structure of information.

Example:

 HTML (HyperText Markup Language)

2. Styling Language

A styling language (or style sheet language) is used to control the appearance and layout of a
structured document (like HTML).
It changes how things look, not what they mean.

Purpose:

To design or style the web page — color, size, spacing, fonts, etc.

Example:

 CSS (Cascading Style Sheets)

3. Functional (Programming) Language

A functional language (or scripting/programming language) is used to add logic and


interactivity to the webpage or program.

It can perform calculations, make decisions, and respond to user actions.

Purpose:

To make web pages interactive and dynamic.

Example:

 JavaScript
Summary Table
Example
Type Purpose Example Usage
Language

Markup Structure of content HTML Defines headings, paragraphs, images

Styling Visual design CSS Sets colors, fonts, layout

Interactivity and Adds actions, calculations, dynamic


Functional JavaScript
logic content

Scripting Languages

A scripting language is a lightweight programming language used to automate tasks,


control software applications, or add interactivity to web pages.

Unlike traditional programming languages (like C or Java), scripting languages are interpreted
(not compiled).

Types of Scripting Languages

1. Client-Side Scripting Languages:

Client-side scripting languages run inside the web browser (on the user’s device).
They are mainly used for user interaction, form validation, animations, and dynamic content.

Common Languages:

 JavaScript
 VBScript (now outdated)

2. Server-Side Scripting Languages

Server-side scripting runs on the web server before the page is sent to the user’s browser.
It’s mainly used for database connectivity, form handling, user authentication, etc.

Common Languages:

 PHP
 Python (with Django/Flask)
 [Link] (JavaScript on server)
 ASP (Active Server Pages)
 Ruby on Rails
Introduction to JavaScript

Definition:

JavaScript is a scripting language used to make web pages interactive, dynamic, and user-
friendly. It runs directly in the web browser and allows developers to control web page
behavior. It is often called the “language of the web” because almost every modern website
uses JavaScript.

Main Points about JavaScript

 It is a lightweight, interpreted scripting language.


 It can be embedded directly into HTML pages.
 It runs on the client-side (in the user’s browser).
 It can also be used on the server-side using [Link].
 It follows Object-Oriented Programming (OOP) concepts.
 It can manipulate HTML and CSS to create dynamic effects.

History of JavaScript
Year Event

Brendan Eich, a programmer at Netscape, developed JavaScript in just 10 days.


1995
Initially, it was called Mocha.

1995 Renamed to LiveScript, and then finally to JavaScript for marketing reasons (to ride
(Later) on Java’s popularity).

1996 Microsoft created a similar language called JScript for Internet Explorer.

1997 JavaScript was submitted to ECMA International for standardization.

1999 – Multiple ECMAScript versions were released to improve functionality and browser
2009 support.

ECMAScript 6 (ES6) was released — a major update with new features like let,
2015
const, arrow functions, and classes.

JavaScript is a core technology of the web, alongside HTML and CSS, and is used
Today
everywhere — from websites to mobile apps and even IoT devices.
Full Form of ECMAScript

ECMAScript (ES) = European Computer Manufacturers Association Script


It is the official standard on which JavaScript is based.

Example:
JavaScript version ES6 means ECMAScript 2015, which introduced modern features.

Advantages of JavaScript

 Easy to learn and use


 Reduces server load
 Provides dynamic and interactive effects
 Supported by all modern browsers
 Huge community and libraries

How to Add JavaScript in a Webpage

JavaScript can be added to an HTML webpage in three main ways:

Inline JavaScript

In this method, JavaScript code is written directly inside an HTML tag using an event handler
attribute, such as onclick, onmouseover, onchange, etc.

Syntax:

<tagname event="JavaScript code"></tagname>

Example:

<html>
<head>
<title>Inline JavaScript Example</title>
</head>
<body>
<h2>Inline JavaScript Example</h2>
<button This is Inline JavaScript.')">Click Me</button>
</body>
</html>
Internal JavaScript

Internal JavaScript is written inside <script> tags in the same HTML file.
It is placed either in the <head> or <body> section.

Syntax:

<script>
// JavaScript code here
</script>

Example (Inside <head>):

<html>
<head>
<title>Internal JavaScript Example</title>
<script>
function msg()
{
alert("Welcome to Internal JavaScript!");
}
</script>
</head>
<body>
<h2>Click the Button Below</h2>
<button Me</button>
</body>
</html>

Example (Inside <body>):

<!DOCTYPE html>
<html>
<head>
<title>Internal Script in Body</title>
</head>
<body>
<script>
function msg()
{
alert("Welcome to Internal JavaScript!");
}
</script>
<h2>Click the Button Below</h2>
<button Me</button>
</body>
</html>
External JavaScript

External JavaScript means writing your script code in a separate .js file and linking it to your
HTML file using the <script src=""> tag.
This method is best for large projects or when the same script is used on multiple pages.

Syntax:

<script src="[Link]"></script>

Step-by-Step Example:

Step 1: Create an HTML file → [Link]


<html>
<head>
<title>External JavaScript Example</title>
<script src="[Link]">
</script>
</head>
<body>
<h2>External JavaScript Example</h2>
<button Here</button>
</body>
</html>

Step 2: Create a JavaScript file → [Link]


function showMessage()
{
alert("Hello! This message is from an external JavaScript file.");
}

Data Types in JavaScript

In JavaScript, data types define the type of value a variable can hold. JavaScript is a
dynamically typed language, which means you don’t need to declare the data type of a
variable — it is determined automatically at runtime based on the value assigned.

Main Categories of Data Types

JavaScript has two main categories of data types:

1. Primitive Data Types


2. Non-Primitive (Reference) Data Types
1. Primitive Data Types

These are the basic and immutable types. There are 6 primitive data types:

(a) Number

Used to represent both integer and floating-point numbers.

Example:

let age = 25; // integer


let price = 99.99; // decimal number
let temperature = -10;
[Link](typeof age); // Output: number

(b) String

Represents a sequence of characters enclosed in single (' '), double (" "), or backticks ( ).

Example:

let name = "Pramod";


let city = 'Delhi';
let message = “Hello” + name;
[Link](message); // Output: Hello Pramod!

(c) Boolean

Holds true or false values — mostly used in conditions and comparisons.

Example:

let isStudent = true;


let hasPassed = false;
[Link] (typeof isStudent); // Output: boolean

(d) Undefined

A variable that has been declared but not assigned a value.

Example:

let x;
[Link](x); // Output: undefined
[Link] (typeof x); // Output: undefined

(e) Null

Represents an intentional absence of [Link] is not the same as undefined.

Example:

let person = null;


[Link](person); // Output: null
[Link](typeof person); // Output: object

(f) BigInt (ES11 / ES2020)

Used for very large numbers beyond the safe integer limit of Number.

Example:

let bigNumber = 1234567890123456789012345678901234567890n;


[Link](typeof bigNumber); // Output: bigint

2. Non-Primitive (Reference) Data Types

These types can store multiple values and are mutable.

(a) Object

Used to store key-value pairs.

Example:

let student = {
name: "Pramod",
age: 20,
isPassed: true
};
[Link]([Link]); // Output: Pramod

(b) Array

A collection of values (can be of any data type).


Example:

let fruits = ["Apple", "Banana", "Mango"];


[Link](fruits[1]); // Output: Banana

(c) Function

A block of code designed to perform a particular task.

Example:

function msg()
{
return "Hello World!";
}
[Link](msg()); // Output: Hello World!

Variables in JavaScript

A variable in JavaScript is a container (storage location) used to store data or values that can
be used and modified later in the program. You can think of it like a box with a name that holds
some information.

Syntax
keyword variableName = value;

Why Variables Are Used

 To store data values (numbers, strings, objects, etc.)


 To reuse data in different parts of the program
 To make code readable and maintainable

Rules for Naming Variables (Identifiers)

1. Variable names must start with a letter, underscore (_) or dollar sign ($)
Example:

Valid:

name, _count, $price


Invalid:

1name, @data

2. Names are case-sensitive


Name and name are different.
3. Reserved keywords like var, for, if, class cannot be used as names.
4. Use meaningful names:
let totalMarks = 95;
let x = 95; (not prefer)

Types of Variables (Based on Declaration Keywords)

There are three main ways to declare variables in JavaScript:

Keyword Scope Reassignment

var Function-scoped Allowed

let Block-scoped Allowed

const Block-scoped Not allowed

1. var Keyword

 The oldest way to declare variables


 Function-scoped (not block-scoped)
 Can be redeclared and updated

Example:

var name = "Pramod";


[Link](name); // Output: Pramod

var name = "Amit"; // Redeclaration allowed


[Link](name); // Output: Amit

2. let Keyword

 Introduced in ES6 (2015)


 Block-scoped (only works inside { })
 Can be updated but not redeclared
Example:

let age = 20;


age = 25; // allowed (update)
[Link](age); // Output: 25

Block Scope Example:

{
let city = "Delhi";
[Link](city); // Output: Delhi
}
[Link](city); // Error: city is not defined

3. const Keyword

 Introduced in ES6
 Block-scoped
 Cannot be redeclared or updated
 Must be initialized at the time of declaration

Example:

const country = "India";


[Link](country); // Output: India

// Not allowed
// country = "USA"; // Error
// const country; // Error: must initialize

Operator in JavaScript
An operator is a special symbol that tells the JavaScript engine to perform a specific
operation on one or more values (called operands).

Every operator performs a particular kind of task like addition, comparison, assignment, or
logical testing. The values (numbers, strings, variables, etc.) that operators work on are called
operands.

Depending on how many operands an operator acts upon, it can be:

 Unary Operator → works on one operand


 Binary Operator → works on two operands
 Ternary Operator → works on three operands
Example 1: Binary Operator

let a = 10;
let b = 5;
let result = a + b;

Here:

 + is the operator
 a and b are operands
 It performs addition operation
Output: 15

Example 2: Unary Operator

let a = 5;
a++; // increment by 1

Here:

 ++ is a unary operator (works on one operand)


 It increases a by 1
Output: 6

Example 3: Ternary Operator

let age = 18;


let result = (age >= 18) ? "Adult" : "Minor";

Here:

 ? and : together make the ternary operator


 It checks a condition and returns a value based on true or false
Output: "Adult"

Types of Operators in JavaScript


Type Description

1. Arithmetic Operators Perform mathematical calculations

2. Assignment Operators Assign values to variables

3. Comparison (Relational) Operators Compare two values


Type Description

4. Logical Operators Combine multiple conditions

5. Bitwise Operators Perform operations at the bit level

6. String Operators Used for string concatenation

7. Ternary (Conditional) Operator Acts as a shorthand for if-else

8. Type Operators Used to check or convert types

1. Arithmetic Operators

Used to perform basic mathematical operations.

Operator Description Example Output

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division 10 / 5 2

% Modulus (Remainder) 10 % 3 1

** Exponentiation 2 ** 3 8

++ Increment a++ increases by 1

-- Decrement a-- decreases by 1

Example:

let a = 10, b = 3;
[Link](a + b); // 13
[Link](a - b); // 7
[Link](a * b); // 30
[Link](a / b); // 3.3333
[Link](a % b); // 1
[Link](a ** b); // 1000

2. Assignment Operators

Used to assign values to variables.

Operator Example Meaning

= x = 10 Assigns value 10 to x

+= x += 5 x=x+5

-= x -= 3 x=x-3

*= x *= 2 x=x*2

/= x /= 4 x=x/4

%= x %= 3 x=x%3

**= x **= 2 x = x ** 2

Example:

let x = 10;
x += 5; // x = 15
x *= 2; // x = 30
[Link](x); // Output: 30

3. Comparison (Relational) Operators

Used to compare two values and return a Boolean (true or false).

Operator Description Example Output

== Equal to (value only) 5 == "5" True

=== Strict equal (value + type) 5 === "5" False

!= Not equal to (value only) 5 != "6" True


Operator Description Example Output

!== Strict not equal (value + type) 5 !== "5" True

> Greater than 10 > 5 True

< Less than 10 < 5 False

>= Greater than or equal to 10 >= 10 True

<= Less than or equal to 10 <= 5 False

Example:

let a = 5, b = "5";
[Link] (a == b); // true
[Link] (a === b); // false
[Link] (a != b); // false
[Link] (a !== b); // true

4. Logical Operators

Used to combine multiple conditions.

Operator Name Description Example Output

&& AND True if both conditions are true (5 > 2 && 10 > 5) true

|| OR True if any one condition is true (5 > 2 || 10 < 5) True

! NOT Reverses the condition !(5 > 2) false

Example:

let age = 18;


[Link] (age > 10 && age < 20); // true
[Link] (age > 20 || age < 15); // false
[Link] (!(age == 18)); // false
5. Bitwise Operators

Work on binary (bit) values directly.

Operator Description Example Binary Output

& AND 5&1 0101 & 0001 = 0001 → 1

| OR 5|1 `0101 | 0001 = 0101 -> 5

^ XOR 5^1 0101 ^ 0001 = 0100 → 4

~ NOT ~5 -(5+1) → -6

<< Left shift 5 << 1 10

>> Right shift 5 >> 1 2

Example:

[Link](5 & 1); // 1


[Link](5 | 1); // 5
[Link](5 ^ 1); // 4
[Link](~5); // -6
[Link](5 << 1);// 10
[Link](5 >> 1);// 2

6. String Operators

Used to join (concatenate) strings.

Operator Description Example Output

+ Concatenation "Hello" + " World" "Hello World"

+= Append msg += "!" "Hello!"

Example:
let firstName = "Pramod";
let lastName = "Kumar";
let fullName = firstName + " " + lastName;
[Link](fullName); // Output: Pramod Kumar

7. Ternary (Conditional) Operator

A short form of if...else.

Syntax:

condition ? expression_if_true : expression_if_false;

Example:

let age = 18;


let result = (age >= 18) ? "Eligible to vote" : "Not eligible";
[Link](result); // Output: Eligible to vote

🔹 8. Type Operators
Operator Description Example Output

typeof Returns type of variable typeof 123 "number"

instanceof Checks if object is instance of class arr instanceof Array true

Example:

let name = "Pramod";


let arr = [1, 2, 3];

[Link](typeof name); // string


[Link](arr instanceof Array); // true

prompt() function:

The prompt() function displays a dialog box that asks the user to input some text. It is mostly
used in browser-based JavaScript programs.

Example 1: Simple Input

<html>
<body>
<script>
let name = prompt("Enter your name:");
[Link]("Hello " + name + "! Welcome to JavaScript.");
</script>
</body>
</html>

Example 2: Taking Two Numbers and Adding Them

<html>
<body>
<script>
let num1 = prompt("Enter first number:");
let num2 = prompt("Enter second number:");

let sum = parseInt(num1) + parseInt(num2);

[Link]("The sum is: " + sum);


</script>
</body>
</html>
Conditional Statements

Conditional statements in JavaScript are used to perform different actions based on different
conditions.
They allow the program to make decisions depending on whether a condition is true or false.

Types of Conditional Statements in JavaScript

1. if statement
2. if...else statement
3. if...else if...else ladder
4. switch statement
5. Ternary operator (? :)

1. if Statement

The if statement executes a block of code only if the condition is true.

Syntax:

if (condition)
{
// code to be executed if condition is true
}

Example:

<script>
let age = 18;

if (age >= 18)


{
[Link]("You are eligible to vote.");
}
</script>

Output:

You are eligible to vote.

2. if...else Statement

The if...else statement executes one block of code if the condition is true, and another block if
the condition is false.

Syntax:
if (condition)
{
// code if condition is true
}
else
{
// code if condition is false
}

Example:

<script>
let marks = 40;

if (marks >= 50)


{
[Link]("You passed the exam!");
}
else
{
[Link]("You failed the exam.");
}
</script>

Output:

You failed the exam.

3. if...else if...else Ladder

This structure is used when you have multiple conditions to check one after another.

Syntax:

if (condition1)
{
// code if condition1 is true
}
else if (condition2)
{
// code if condition2 is true
}
else
{
// code if all conditions are false
}

Example:

<script>
let percentage = 85;

if (percentage >= 90)


{
[Link]("Grade: A+");
}
else if (percentage >= 75)
{
[Link]("Grade: A");
}
else if (percentage >= 60)
{
[Link]("Grade: B");
}
else if (percentage >= 40)
{
[Link]("Grade: C");
}
else
{
[Link]("Fail");
}
</script>

Output:

Grade: A

4. switch Statement

The switch statement is used to perform different actions based on different values of a
variable.

Syntax:

switch(expression)
{
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}

Example:

<script>
let day = 3;
let dayName;

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

[Link]("Today is " + dayName);


</script>

Output:

Today is Wednesday
5. Ternary Operator ( ? : )

The ternary operator is a shortcut for the if...else statement. It takes three operands: condition,
value if true, and value if false.

Syntax:

condition ? value_if_true : value_if_false;

Example:

<script>
let age = 20;
let result = (age >= 18) ? "Adult" : "Minor";
[Link](result);
</script>

Output:

Adult

Looping Statement

A loop is a control structure that allows you to execute a block of code repeatedly as long as a
specified condition is true. It helps reduce code repetition and makes programs shorter and more
efficient.

Types of Loops in JavaScript

1. for loop
2. while loop
3. do...while loop
4. for...in loop
5. for...of loop

1. for Loop

The for loop is used when you know in advance how many times you want to execute a
statement or block of statements.

Syntax:

for(initialization; condition; increment/decrement)


{
// code to be executed
}
Example 1: Print numbers from 1 to 5

<script>
for (let i = 1; i <= 5; i++)
{
[Link](i + "<br>");
}
</script>

Output:

1
2
3
4
5

Example 2: Sum of first 5 numbers

<script>
let sum = 0;
for (let i = 1; i <= 5; i++)
{
sum = sum + i;
}
[Link]("Sum = " + sum);
</script>

Output:

Sum = 15

2. while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax:

while (condition)
{
// code to be executed
}

Example:

<script>
let i = 1;
while (i <= 5)
{
[Link](i + "<br>");
i++;
}
</script>

Output:

1
2
3
4
5

3. do...while Loop

The do...while loop is similar to the while loop, except it executes the code block at least once,
even if the condition is false.

Syntax:

do
{
// code to be executed
} while (condition);

Example:

<script>
let i = 1;
do
{
[Link](i + "<br>");
i++;
} while (i <= 5);
</script>
Output:

1
2
3
4
5

Note: The condition is checked after executing the code block once.

4. for...in Loop

The for...in loop is used to iterate over the properties (keys) of an object.

Syntax:

for (let key in object)


{
// code to be executed
}

Example:

<script>
let person = {name: "Pramod", age: 25, city: "Delhi"};

for (let key in person)


{
[Link](key + " : " + person[key] + "<br>");
}
</script>

Output:

name : Pramod
age : 25
city : Delhi

5. for...of Loop

The for...of loop is used to iterate over iterable objects such as arrays, strings, or sets.

Syntax:

for (let variable of iterable)


{
// code to be executed
}

Example 1: Iterating through an array

<script>
let fruits = ["Apple", "Banana", "Mango"];

for (let fruit of fruits)


{
[Link](fruit + "<br>");
}
</script>

Output:

Apple
Banana
Mango

Example 2: Iterating through a string

<script>
let name = "RAM";

for (let char of name)


{
[Link](char + "<br>");
}
</script>

Output:

R
A
M

JavaScript Popup Boxes

JavaScript Popup Boxes are built-in browser dialog boxes used to interact with users — such
as displaying messages, asking for confirmation, or taking input.

They are simple pop-up windows that appear in front of the web page.
Types of JavaScript Popup Boxes

JavaScript provides three main types of popup boxes:

1. alert() box
2. confirm() box
3. prompt() box

1. alert() Box

The alert() box is used to display a message to the user.


It is mostly used to give information, warnings, or notifications.

Syntax:

alert("message");

Example 1: Simple Alert

<html>
<body>
<script>
alert("Welcome to JavaScript!");
</script>
</body>
</html>

Explanation:

 The browser displays a pop-up with the message:


"Welcome to JavaScript!"
 The user must click OK to continue.

Example 2: Alert after clicking a button

<!DOCTYPE html>
<html>
<body>
<button Me</button>

<script>
function showAlert()
{
alert("Button was clicked!");
}
</script>
</body>
</html>

Explanation:

 When the user clicks the button, the message box appears.

2. confirm() Box

The confirm() box is used to ask the user for confirmation — typically for Yes/No or
OK/Cancel type questions.
It returns:

 true → if the user clicks OK


 false → if the user clicks Cancel

Syntax:

confirm("message");

Example 1: Simple Confirm Box

<!DOCTYPE html>
<html>
<body>
<script>
let result = confirm("Do you want to continue?");
if (result)
{
[Link]("You pressed OK!");
}
else
{
[Link]("You pressed Cancel!");
}
</script>
</body>
</html>

Output (possible results):

You pressed OK!

or

You pressed Cancel!


Explanation:

 If the user clicks OK, confirm() returns true.


 If the user clicks Cancel, it returns false.

Example 2: Confirm before deleting data

<!DOCTYPE html>
<html>
<body>
<button Data</button>

<script>
function deleteData()
{
let confirmDelete = confirm("Are you sure you want to delete this data?");
if (confirmDelete)
{
alert("Data deleted successfully!");
}
else
{
alert("Delete action canceled.");
}
}
</script>
</body>
</html>

Explanation:

 The user is asked for confirmation before performing a delete operation.

3. prompt() Box

The prompt() box is used to take input from the user.


It always returns the input as a string.

Syntax:

prompt("message", "default value");

Example 1: Take user name

<html>
<body>
<script>
let name = prompt("Enter your name:");
[Link]("Hello, " + name + "!");
</script>
</body>
</html>

Output:

Hello, Pramod!

Example 2: Taking two numbers and showing sum

<html>
<body>
<script>
let a = prompt("Enter first number:");
let b = prompt("Enter second number:");
let sum = parseInt(a) + parseInt(b);
alert("The sum is: " + sum);
</script>
</body>
</html>

Explanation:

 prompt() collects the input as strings.


 parseInt() converts them into numbers for addition.

Array in JavaScript

An Array in JavaScript is a special type of variable that can store multiple values in a single
variable name, instead of creating separate variables for each value.

Arrays are ordered collections of elements, which can be numbers, strings, objects, or even
other arrays.

Syntax of Array
let array_name = [value1, value2, value3, ...];

Example:

let fruits = ["Apple", "Banana", "Mango"];

Here:
 fruits is an array.
 It contains 3 elements → "Apple", "Banana", "Mango".

Ways to Create an Array

1. Using Array Literal (Most Common Way)

let colors = ["Red", "Green", "Blue"];

2. Using the new Array() Constructor

let numbers = new Array(10, 20, 30, 40);

3. Creating an Empty Array and Adding Elements Later

let animals = [];


animals[0] = "Dog";
animals[1] = "Cat";
animals[2] = "Cow";

Accessing Array Elements

You can access elements using their index number (starting from 0).

let fruits = ["Apple", "Banana", "Mango"];


[Link](fruits[0]); // Output: Apple
[Link](fruits[2]); // Output: Mango

Changing Array Elements

You can modify elements directly using their index:

let fruits = ["Apple", "Banana", "Mango"];


fruits[1] = "Orange";
[Link](fruits); // Output: Apple,Orange,Mango

Array Length Property

You can find the number of elements in an array using .length.

let fruits = ["Apple", "Banana", "Mango"];


[Link]("Number of fruits: " + [Link]);

Output:
Number of fruits: 3

Looping Through an Array

Example using for loop:

<script>
let fruits = ["Apple", "Banana", "Mango", "Orange"];

for (let i = 0; i < [Link]; i++)


{
[Link](fruits[i] + "<br>");
}
</script>

Output:

Apple
Banana
Mango
Orange

Example using for...of loop:

<script>
let fruits = ["Apple", "Banana", "Mango"];

for (let fruit of fruits)


{
[Link](fruit + "<br>");
}
</script>
JavaScript Events

An event in JavaScript is an action or occurrence that happens in the browser, which the
program can respond to.

👉 Events are things like:

 A user clicking a button


 A web page loading
 A key being pressed
 A form being submitted
 The mouse moving

JavaScript allows you to “listen” for these events and then execute code (called an event
handler) when they occur.

🧩 Common Examples of Events


Event Name Description

onclick Occurs when a user clicks on an element

onmouseover Occurs when the mouse pointer is moved over an element

onmouseout Occurs when the mouse pointer is moved out of an element

onkeydown Occurs when a key is pressed

onkeyup Occurs when a key is released

onload Occurs when the page has finished loading

onchange Occurs when the value of an element is changed

onsubmit Occurs when a form is submitted

ondblclick Occurs when an element is double-clicked

onfocus Occurs when an element gets focus (like a text box)

onblur Occurs when an element loses focus


Types of Event Handling in JavaScript

There are 3 main ways to handle events:

1. Inline Event Handling (in HTML tag)

You can write the event directly inside an HTML element.

<!DOCTYPE html>
<html>
<body>

<h2>Inline Event Example</h2>


<button You clicked the button')">Click Me</button>

</body>
</html>

When the user clicks the button → an alert box appears.

2. Event Handling using HTML DOM (via JavaScript)

You can assign an event handler to an HTML element inside a <script> tag.

<!DOCTYPE html>
<html>
<body>

<h2>DOM Event Example</h2>


<button id="myBtn">Click Me</button>

<script>
[Link]("myBtn"). >{
alert("Button clicked using DOM event handling!");
}
</script>

</body>
</html>

JavaScript accesses the button by id and assigns an event function to it.

3. Event Listener Method (Recommended Modern Way)


This is the best and modern method to handle multiple or complex events.

<!DOCTYPE html>
<html>
<body>

<h2>addEventListener() Example</h2>
<button id="btn">Click Me</button>

<script>
[Link]("btn").addEventListener("click", function()
{
alert("Hello! You used addEventListener()");
});
</script>

</body>
</html>

JavaScript Objects

An object is a collection of properties, and each property is defined as a key-value pair.

An object stores multiple values as a single unit using name-value pairs.

Syntax:

let objectName = {
key1: value1,
key2: value2,
key3: value3
};

Example:

let student = {
name: "Aarav",
age: 20,
course: "BCA",
isPassed: true
};

Here:

 name, age, course, isPassed are keys (properties)


 "Aarav", 20, "BCA", true are values
Accessing Object Properties

[Link] Dot Notation:

[Link]([Link]); // Output: Aarav

[Link] Bracket Notation:

[Link](student["age"]); // Output: 20

Adding and Modifying Properties

[Link] = "Delhi"; // Adding new property


[Link] = 21; // Modifying existing property

Deleting a Property

delete [Link];

JavaScript Functions

A function is a block of code designed to perform a specific task.


It runs only when it is called (invoked). A function is like a machine — you give it some input,
it does work, and gives output.

Syntax:

function functionName(parameter1, parameter2)


{
// code to be executed
}

Example 1: Simple Function

function msg()
{
alert("Welcome to JavaScript!");
}

msg(); // Function call

Example 2: Function with Parameters

function add(a, b)
{
return a + b;
}

let result = add(10, 20);


[Link]("Sum = " + result); // Output: Sum = 30

Example 3: Function Returning Value

function multiply(x, y)
{
let result = x * y;
return result;
}

[Link](multiply(4, 5)); // Output: 20

JavaScript Form Validation

Form Validation means checking whether the user has filled in all fields correctly before the
form is submitted.

It ensures:

 Required fields are not empty


 Email, phone, and password formats are correct
 Data entered by the user is valid before sending to the server

Types of Form Validation


Type Description

Client-side validation Done in the browser using JavaScript before sending data to the server

Server-side validation Done on the server after the form is submitted

Usually, we perform client-side validation using JavaScript to save time and improve user
experience.

Basic Example: Empty Field Validation


<html>
<head>
<title>Form Validation Example</title>
<script>
function validateForm()
{
let name = [Link];

if (name == "")
{
alert("Name must be filled out!");
return false; // prevent form submission
}
return true; // allow form submission
}
</script>
</head>

<body>
<h2>Simple Form Validation</h2>

<form name="myForm" validateForm()">


Name: <input type="text" name="username"><br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

Example 2: Email Validation


<html>
<head>
<title>Email Validation</title>
<script>
function validateEmail()
{
let email = [Link];
let pattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/; // email pattern

if (![Link](pattern))
{
alert("Please enter a valid email address!");
return false;
}
return true;
}
</script>
</head>

<body>
<h2>Email Validation Example</h2>

<form name="myForm" validateEmail()">


Email: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

Example 3: Multiple Field Validation (Name, Email, Password)


<!DOCTYPE html>
<html>
<head>
<title>Full Form Validation</title>
<script>
function validateForm() {
let name = [Link];
let email = [Link];
let password = [Link];

let emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;

if (name == "") {
alert("Please enter your name!");
return false;
}
if (![Link](emailPattern)) {
alert("Please enter a valid email!");
return false;
}
if ([Link] < 6) {
alert("Password must be at least 6 characters long!");
return false;
}

alert("Form submitted successfully!");


return true;
}
</script>
</head>

<body>
<h2>Form Validation Example</h2>
<form name="myForm" validateForm()">
Name: <input type="text" name="name"><br><br>
Email: <input type="text" name="email"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

Example 4: Numeric Input Validation (Phone Number)


<!DOCTYPE html>
<html>
<head>
<title>Phone Number Validation</title>
<script>
function validatePhone() {
let phone = [Link];
let pattern = /^[0-9]{10}$/; // exactly 10 digits

if (![Link](pattern)) {
alert("Please enter a valid 10-digit phone number!");
return false;
}
return true;
}
</script>
</head>

<body>
<h2>Phone Number Validation</h2>

<form name="myForm" validatePhone()">


Phone: <input type="text" name="phone"><br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

Example 5: Password and Confirm Password Validation


<!DOCTYPE html>
<html>
<head>
<title>Password Validation</title>
<script>
function checkPassword()
{
let pass1 = [Link];
let pass2 = [Link];

if (pass1 == "" || pass2 == "")


{
alert("Both password fields are required!");
return false;
}
if (pass1 != pass2)
{
alert("Passwords do not match!");
return false;
}
alert("Passwords matched successfully!");
return true;
}
</script>
</head>

<body>
<h2>Password Validation</h2>

<form name="myForm" checkPassword()">


Password: <input type="password" name="password"><br><br>
Confirm Password: <input type="password" name="confirm"><br><br>
<input type="submit" value="Submit">
</form>

</body>
</html>

You might also like