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

Unit 3 JavaScript

This document provides an overview of JavaScript, covering its role in web development, variable declarations, data types, functions, and the DOM. It explains the differences between primitive and non-primitive data types, demonstrates how to create and manipulate objects and arrays, and introduces various methods for displaying output. Additionally, it includes examples of using the Math and Date objects, as well as a simple digital clock program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views43 pages

Unit 3 JavaScript

This document provides an overview of JavaScript, covering its role in web development, variable declarations, data types, functions, and the DOM. It explains the differences between primitive and non-primitive data types, demonstrates how to create and manipulate objects and arrays, and introduces various methods for displaying output. Additionally, it includes examples of using the Math and Date objects, as well as a simple digital clock program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Web Technology

Unit-3
Javascript

Prof. Anand Singh


Unit-3
• Scripting: Java script: Introduction, documents,
forms, statements, functions, objects, introduction
to AJAX.
• Networking: Internet Addressing, InetAddress,
Factory Methods, Instance Methods, TCP/IP Client
Sockets, URL, URL Connection, TCP/IP Server
Sockets, Datagram.
What is JavaScript?
JavaScript (JS) is a high-level, interpreted programming language that is mainly used
to make web pages interactive and dynamic.
•Without JavaScript → a webpage is just HTML (structure) + CSS (style).
•With JavaScript → you can add logic, interactivity, and behavior.

👉 That’s why we call JavaScript the “brain of the web page”.

•HTML = skeleton of a body (structure).


•CSS = clothes and makeup (appearance).
•JavaScript = brain (makes it move, think, and respond).
🔹 Example: A Simple JavaScript Program

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<h1 id="demo">Hello world!</h1>

<script>
// Change text when page loads
document.getElementById("demo").innerHTML = "Hello from JavaScript!";
</script>
</body>
</html>

👉 This changes the heading text using JavaScript.


Variables in JavaScript  variables are containers for data.
 JavaScript variables can be declared in 4 ways:
Older JavaScript

•Using var (Not Recommended)


•Automatically (Not Recommended)

Modern JavaScript

•Using let
•Using const

🔹 1. var
•Can be re-declared and updated in the same scope.
•It is function-scoped (or globally scoped if not inside a function).
<script>
var x = 10;
var x = 20; // ✅ re-declaration allowed
x = 30; // ✅ update allowed
console.log(x); // 30
</script>
⚠️This can cause bugs, so var is rarely used in modern JavaScript.
🔹 2. let
•Can be updated, but NOT re-declared in the same scope.
•It is block-scoped (works only inside {} block).
<script>
let y = 10;
y = 20; // ✅ update allowed
// let y = 30; ❌ Error: Identifier 'y' has already been declared
console.log(y);
<script>
But in a different block, you can declare it again:

<script>
let z = 5;
{
let z = 100; // ✅ new variable (different scope)
console.log(z); // 100
}
console.log(z); // 5
</script>
🔹 3. const
 Cannot be re-declared or updated.
 Must be initialized at the time of declaration.
 Also block-scoped.

<script>
const PI = 3.14;
// PI = 3.1415; ❌ Error: Assignment to constant variable
// const PI = 3.1415; ❌ Error: Already declared
console.log(PI);
</script>

🔹 4.Declaring a Variable Without var, let, or const


 If you just assign a value to a name without using var, let, or const,
JavaScript will automatically create a global variable.

<script>
x = 10; // no var, let, or const
console.log(x); // 10
<script>
✅ It works — but behind the scenes, JavaScript adds x to the global scope

🔹 Problems with This


 Accidental Globals
If you forget let/const, you might create unwanted global variables:

<script>
function test() {
y = 100; // forgot let
}
test();
console.log(y); // 100 😱 becomes global!
</script>

✅ Best Practice
 Always use let (if value changes) or const (if fixed).
 Avoid declaring variables without a keyword.
// Example: variable declarations in JavaScript
<script>
console.log("=== Using var ===");
var a = 10;
var a = 20; // ✅ re-declared
a = 30; // ✅ updated
console.log("a =", a); // 30

console.log("\n=== Using let ===");


let b = 10;
// let b = 20; ❌ Error: Cannot re-declare in same scope
b = 20; // ✅ update allowed
console.log("b =", b); // 20

console.log("\n=== Using const ===");


const c = 10;
// const c = 20; ❌ Error: Cannot re-declare
// c = 30; ❌ Error: Cannot update
console.log("c =", c); // 10
function test() {
console.log("\n=== Without var/let/const ==="); e = 50; // ⚠️becomes global, even inside
d = 10; // ⚠️Implicit global function
d = 20; // ✅ update allowed }
console.log("d =", d); // 20 test();
</script> console.log("e =", e); // 50 (unexpected!)
Different ways to display output in Javascript
 In JavaScript, there are several ways to display output depending on where you
want to show it—web page, console, or pop-up.
1. Using console.log()
 This is mostly used for debugging.
console.log("Hello World"); // General output

✅ Output goes to the browser console.

2. Using alert() (Pop-up box)


 Displays a popup alert box in the browser.
alert("Hello JavaScript!");
⚠️This interrupts the user experience; mostly used for simple testing.

3. Using document.write() (Directly on page)

 Writes content directly into the HTML page.


document.write("Hello World!");

⚠️Not recommended after the page has loaded because it overwrites the entire page.
4. Using innerHTML (Inject into HTML element)

 Displays output inside an HTML element.

<div id="output"></div>
<script>
document.getElementById("output").innerHTML = “Welcome to javascript!";
</script>

✅ Safe and widely used for dynamic content.


Data Types in JavaScript
 Data types tells what kind of value a variable holds.
 There are two main categories:

1.Primitive Data Types → simple, single values


2.Non-Primitive Data Types (Objects) → more complex, can store multiple values

11️⃣Primitive Data Types


These are simple and immutable (cannot be changed once created).
a) Number
•Represents numeric values (both integers and decimals).
Example:
<script>
let age = 20; // integer
let price = 99.99; // decimal
console.log(age, price);
</script>

b) String
•Text enclosed in single quotes ' ', double quotes " ", or backticks ` ` (for templates
Example:
<script>
let name = "Anil";
let greeting = 'Hello World';
let message = `Welcome ${name}!`; // Template literal
console.log(name, greeting, message);
</script>
c) Boolean
•Represents true or false.
Example: <script>
let isStudent = true;
let hasGraduated = false;
console.log(isStudent, hasGraduated);
</script>
Undefined
ariable that has been declared but hasn't been given a value yet.
like an empty container.
Example: A new volunteer signs up but we haven't assigned
them a job yet.
let volunteerJob;
console.log(volunteerJob); // Output: undefined
e) Null:
It explicitly means "nothing" or "empty." It's not undefined; we
are choosing to say there's no value here.
Example: The popcorn machine is broken and is out of service until
let popcornMachine = null;
console.log(popcornMachine); // Output: null

2 Non-Primitive Data Type


2️⃣
Object

Array

functions
Object in Javascript:
🔹 Creating Objects in JavaScript
1. Using Object Literal {} (most common)
<script>
let car = {
brand: "Toyota",
model: "Fortuner",
color: "Black",
start: function() {
return "Car started!";
}
};

//console.log(car.brand); // Toyota
//console.log(car["color"]); // Black
for(let c in car){
console.log(car[c]);
}
console.log(car.start()); // Car started!
</script>
2. Using new Object()

let person = new Object();


person.name = "John";
person.age = 25;

console.log(person.name); // John

3. Using Constructor Function

function Person(name, age) {


this.name = name;
this.age = age;
}

let p1 = new Person("Alice", 30);


console.log(p1.name); // Alice
4. Using ES6 class

class Student {
constructor(name, roll) {
this.name = name;
this.roll = roll;
}
}

let s1 = new Student("Anil", 101);


console.log(s1.name); // Anil
🔹 Arrays in Javascript

🔹 Creating Arrays

Using square brackets (most common):


let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
console.log(fruits[2]); // Mango

🔹 Looping Through Arrays

1. for loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

2. for...of
for (let fruit of fruits) {
console.log(fruit);
}
Using new Array() constructor:

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


for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

Function

🔹 Syntax of a Function

function functionName(parameters) {
// code to execute
return result; // optional
}
🔹 Types of Functions in JavaScript
1.Function Declaration (Named Function)
function display(name) {
return "Hello, " + name;
}
Let d=Display("Anil")
console.log(d); // Hello, Anil

2. Function Expression
(Function stored in a variable.)
let display = function(name) {
return "Hello, " + name;
};
Let d=Display("Anil")
console.log(d); // Hello, Anil
3. Arrow Function (ES6+) (Mostly used )
let display = (name) => "Hello, " + name;
console.log(greet("Student")); // Hello, Student
4. Anonymous Function (Function without a name – often used in
setTimeout, forEach.)
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);

Math Object
JavaScript has a built-in Math object that provides properties and methods for
mathematical calculations.
It is not a constructor, so you cannot do new Math().
You just use it directly → Math.method()
🔹 Common Math Properties

Property Meaning Example


Math.PI Value of π (3.14159…) Math.PI → 3.14159…
Math.E Euler’s number (2.718…) Math.E → 2.718…
Math.SQRT2 Square root of 2 Math.SQRT2 → 1.414…
Math.LN2 Natural log of 2 Math.LN2 → 0.693…

🔹 Common Math Methods


1. Rounding Numbers

Math.round(4.6); // 5
Math.round(4.4); // 4
Math.ceil(4.1); // 5 (round UP)
Math.floor(4.9); // 4 (round DOWN)
Math.trunc(4.9); // 4 (just remove decimals)

2. Power and Roots

Math.pow(2, 3); // 8 (2³)


Math.sqrt(25); // 5 (√25)
4. Min and Max

Math.min(3, 7, 1, 9); // 1
Math.max(3, 7, 1, 9); // 9

5. Random Numbers

Math.random(); // Random number between 0 and 1


Math.floor(Math.random() * 10); // Random number 0–9
Math.floor(Math.random() * 100) + 1; // Random number 1–100

Example 1: Random Number between 0 and 1

let num = Math.random();


console.log(num);
// Example output: 0.456789 (always between 0 and 1)

Example 2: Random Number between 1 and 10

let num = Math.floor(Math.random() * 10) + 1;


console.log(num);
// Example output: 7 (integer between 1 and 10)
Example: Random Number between Any Range (min–max)

function getRandom(min, max) {


return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(getRandom(50, 100));
// Example output: 73 (integer between 50 and 100)
Example: make a simple interactive Random Number Generator to generate
number between 1 & 100 with a button.

<!DOCTYPE html>
<html>
<head>
<title>Random Number Generator</title>
</head>
<body>
<h2> Random Number Generator</h2>
<p>Click the button to generate a random number between 1 and 100:</p>
<button onclick="generateRandom()">Generate Number</button>
<h3 id="result"></h3>
<script>
function generateRandom() {
let num = Math.floor(Math.random() * 100) + 1;
document.getElementById("result").innerText = "Your Number: " + num;
}
</script>
</body>
</html>
Date Object in JavaScript
 The Date object in JavaScript is used to work with dates and times.
 It allows you to create, format, and manipulate dates.

1. Creating a Date Object


There are 4 main ways to create a date:
// Current date and time
let now = new Date();
console.log(now);
Output:
Tue Sep 30 2025 15:59:42 GMT+0530 (India Standard Time)
// Specific date and time
let d1 = new Date("2025-09-22");
console.log(d1);
Output:
Tue Sep 22 2015 05:30:00 GMT+0530 (India Standard Time)

// Year, Month, Day (Month starts from 0 → Jan=0, Feb=1, ... Dec=11)
let d2 = new Date(2025, 8, 30); // 30 Sep 2025
console.log(d2);
Output
Tue Sep 30 2025 00:00:00 GMT+0530 (India Standard Time)
// Date and time with hours, minutes, seconds
let d3 = new Date(2025, 8, 30, 15, 45, 20);
console.log(d3);
Output:
Tue Sep 30 2025 15:45:20 GMT+0530 (India Standard Time)
2. Important Methods of Date Object

let today = new Date();

console.log(today.getFullYear()); // Year (e.g., 2025)


console.log(today.getMonth()); // Month (0–11)
console.log(today.getDate()); // Day of month (1–31)
console.log(today.getDay()); // Day of week (0–6, Sunday=0)
console.log(today.getHours()); // Hours (0–23)
console.log(today.getMinutes()); // Minutes (0–59)
console.log(today.getSeconds()); // Seconds (0–59)
console.log(today.getMilliseconds());// Milliseconds (0–999)
console.log(today.getTime()); // Timestamp (ms since 1 Jan 1970)
Q: Write a program in JavaScript to display digital clock showing HH:MM:SS.
<!DOCTYPE html>
<head>
</head>
<body>
<h1>Digital Clock</h1>
<p id="clock"></p>
</body>
<script>
function showTime(){
let now=new Date();
let hours=now.getHours();
let minutes=now.getMinutes();
let seconds=now.getSeconds();
if(hours<10) hours="0"+hours;
if(minutes<10) minutes="0"+minutes;
if(seconds<10) seconds= "0"+seconds;
let time=hours+":"+minutes+":"+seconds;
document.getElementById("clock").innerHTML=time;
}
//update every 1 seconds
setInterval(showTime,1000);
showTime();
</script>
</html>
DOM(Document Object Model)
 It is a programming interface for web documents (HTML or XML).
 The browser creates a tree-like structure of the entire web page.
 Each element (like <p>, <h1>, <div>, etc.) becomes a node/object that
JavaScript can access and manipulate.
 The document is the root (grandparent).
 Inside it are parents (like <html>, <body>).
 Inside parents are children (like <h1>, <p>).
 Each tag is connected just like family members in a tree structure.

<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<h1 id=“demo">Hello DOM</h1>
<p class="text">This is a paragraph.</p>
</body>
</html>
⚡ Accessing DOM Elements in JavaScript
JavaScript can select and manipulate DOM elements in many ways:

1. By ID
document.getElementById(“demo").innerHTML = "Welcome to DOM!";

2. By Class

document.getElementsByClassName("text")[0].style.color = "blue";

3. By Tag

document.getElementsByTagName("h1")[0].style.backgroundColor = "yellow";

4. Modern Query Selectors

document.querySelector(".text").innerHTML = "Changed using querySelector!";


document.querySelectorAll("p")[0].style.fontSize = "20px";
Manipulating DOM

1.Change content
document.getElementById(“demo").innerText = "DOM Updated!";

2.Change style
document.querySelector(".text").style.color = "red";

3.Add new element

let newPara = document.createElement("p");


newPara.innerText = "This is a new paragraph.";
document.body.appendChild(newPara);

4.Remove element
let para = document.querySelector(".text");
para.remove();
Example: Adding an element in a web document using JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Adding an Element Example</title>
</head>
<body>
<h2>Student List</h2>
<ul id="studentList">
<li>Rohit</li>
<li>Prakash</li>
</ul>
<button onclick="addStudent()">Add New Student</button>
<script>
function addStudent() {
let newItem = document.createElement("li");
newItem.textContent = "Anil";
document.getElementById("studentList").appendChild(newItem);
}
</script>
</body>
</html>
📘 Example: Change Text with a Button (DOM Manipulation)
script.js
<!DOCTYPE html> // Change text of h1
<head> function changeText() {
<title>DOM Example</title> document.getElementById("title")
<style> .innerText = "Text Changed with DOM!";
#title { }
color: blue; // Change color of h1
font-size: 24px; function changeColor()
} document.getElementById("title").style.color
button { = "green";
margin-top: 10px; }
padding: 8px 15px; // Add new paragraph
font-size: 16px; function addParagraph() {
cursor: pointer; let newPara = document.createElement("p");
} newPara.innerText = "This is a new paragraph
</style> added using DOM.";
</head> document.body.appendChild(newPara);
<body> }
<h1 id="title">Hello DOM!</h1>
<button onclick="changeText()">Change Text</button>
<button onclick="changeColor()">Change Color</button>
<button onclick="addParagraph()">Add Paragraph</button>
<script src=“script.js”>
</body>
Events
•An event is any action or occurrence that happens in the browser and can be
detected by JavaScript.
•Events are usually triggered by the user or the browser.

Examples of events:
•A user clicks a button.
•A user moves the mouse over an element.
•A user presses a key on the keyboard.
•A form gets submitted.

Event Handling
•Event Handling means writing JavaScript code that responds to events.

•You attach a function (called event handler) to an event.

•When the event happens, the function runs automatically.


Example in real life:
•Event = Someone presses a doorbell.
•Event Handler = The bell rings.

Some common Events:


•Mouse Events → onclick, ondblclick, onmouseover, onmouseout
•Keyboard Events → onkeydown, onkeyup
•Form Events → onsubmit, onfocus, onblur
•Window Events → onload, onresize

Ways to Handle Events in JavaScript

Method 1: Inline Event Handling


Write JavaScript directly inside the HTML tag.

<button onclick="alert('Button clicked!')">Click Me</button>


Method 2: Using HTML Properties
 Call a JavaScript function when the event occurs.

<!DOCTYPE html>
<html>
<body>

<h2>Event Handling Example</h2>


<button onclick="showMessage()">Click Me</button>

<script>
function showMessage() {
alert("Hello! You clicked the button.");
}
</script>

</body>
</html>
Method 3: Using addEventListener() (Best Practice)

 This method keeps HTML and JS separate.

<!DOCTYPE html>
<html>
<body>

<h2>Event Listener Example</h2>


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

<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Button was clicked!");
});
</script>

</body>
</html>
Advantages of addEventListener():

•Can attach multiple events to one element.

•Cleaner code (HTML and JS are separate).

Common Events in JavaScript

Event Name Description


onclick When an element is clicked
ondblclick When double-clicked
onmouseover When mouse is moved over element
onmouseout When mouse leaves element
onkeydown When a key is pressed
onkeyup When a key is released
onload When page finishes loading
onsubmit When a form is submitted
Change Text on Click
<!DOCTYPE html>
<html>
<head>
<title>Event Handling Example</title>
</head>
<body>
<h1 id="heading">Hello Students!</h1>
<button id="changeBtn">Change Text</button>
<script>
// Select button and heading
let btn = document.getElementById("changeBtn");
let heading = document.getElementById("heading");

// Add event listener to button


btn.addEventListener("click", function() {
heading.innerText = "You just clicked the button!";
heading.style.color = "blue";
});
</script>
</body>
</html>
Example : Change Text Color on Hover
When you move the mouse over the text → it turns red.
When you move the mouse out → it turns black again.

<!DOCTYPE html>
<html>
<head>
<title>onmouseover and onmouseout Example</title>
</head>
<body>
<h2 onmouseover="this.style.color='red'" onmouseout="this.style.color='black'">
Hover over this text!
</h2>
</body>
</html>
Form Validation Example
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Validation</title>
<style>
.error { color: red; font-size: 14px; }
</style>
</head>
<body>
<h2>Simple Registration Form</h2>
<form onsubmit="return validateForm()">
Name: <input type="text" id="name">
<span class="error" id="nameError"></span><br><br>
Email: <input type="text" id="email">
<span class="error" id="emailError"></span><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
function validateForm() {
// Get values from inputs
let name = document.getElementById("name").value.trim();
let email = document.getElementById("email").value.trim();

// Clear old error messages


document.getElementById("nameError").innerText = "";
document.getElementById("emailError").innerText = "";

let isValid = true;


// Check Name field
if (name === "") {
document.getElementById("nameError").innerText = " * Name is required";
isValid = false;
}

// Check Email field


if (email === "") {
document.getElementById("emailError").innerText = " * Email is required";
isValid = false;
}
return isValid; // If false → form will not submit
}
Q1.Write a program in JavaScript to display digital clock showing HH:MM:SS.

Q2.Design a HTML form with name, address, pincode and password. Outline a JavaScript
code that can validate on following constraints: a. No fields must be left blank b. Pincode
must be numeric and contain 6 digits c. Password field (i) At least contains 1 Capital letter. (ii)
Minimum length 8 characters

Q3.Discuss function in Java Script. Outline a JS function that takes 4 variables, a, b, c, d,


and prints true in an alert box if input a > input b and input c > input d. Else, print false in
an alert box.

Q4.Explain the various event handlers in JavaScript with an example of each. Create a
JavaScript program to make arithmetic calculator

You might also like