0% found this document useful (0 votes)
10 views15 pages

Unit 4 JAVASCRIPT

This document provides an introduction to JavaScript, covering its uses in web development, variable declaration, operators, conditional statements, loops, and functions. It also discusses built-in methods for strings, arrays, and math, as well as event handling and the Document Object Model (DOM). JavaScript is essential for creating dynamic web content and is supported by all modern browsers.

Uploaded by

Soumya Das
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)
10 views15 pages

Unit 4 JAVASCRIPT

This document provides an introduction to JavaScript, covering its uses in web development, variable declaration, operators, conditional statements, loops, and functions. It also discusses built-in methods for strings, arrays, and math, as well as event handling and the Document Object Model (DOM). JavaScript is essential for creating dynamic web content and is supported by all modern browsers.

Uploaded by

Soumya Das
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
You are on page 1/ 15

Unit 5 JAVASCRIPT

Introduction to JavaScript:
JavaScript is a versatile and powerful programming language primarily used for creating
dynamic and interactive content on websites. It is a core technology of the web, alongside
HTML and CSS.

JavaScript can be used for various purposes, such as:


 Manipulating web page content dynamically.
 Responding to user actions and events.
 Communicating with servers for data exchange (e.g., AJAX).
 Building interactive user interfaces.

JavaScript is supported by all modern web browsers and is an essential skill for web developers.
It works seamlessly with HTML to define the structure of a webpage and CSS to style it.
Beyond the browser, JavaScript is widely used on the server side (e.g., Node.js) and in desktop
or mobile applications.

Variables in JavaScript:

Variables are fundamental to programming, allowing you to store and manipulate data. In
JavaScript, variables can be declared using three keywords:

 var: The original way to declare variables. It has function scope and is less commonly used
in modern JavaScript due to certain limitations.

var greeting = "Hello";

 let: Introduced in ES6, it provides block scope, making it safer and more predictable.

let age = 25;

 const: Used to declare constants, values that cannot be reassigned after their initial
assignment. It also has block scope.

const pi = 3.14159;

Rules for Naming Variables:


 Variable names can include letters, digits, underscores, and dollar signs but cannot start with
a digit.
 JavaScript is case-sensitive, so myVar and myvar are different.
 Avoid using reserved keywords as variable names.
Examples:

let userName = "Alice";


const maxScore = 100;
var isActive = true;

Variables can hold different types of data, including strings, numbers, booleans, arrays, objects,
and more. JavaScript is dynamically typed, meaning the type of a variable can change at
runtime.

JavaScript Operators:

JavaScript operators are symbols or keywords that perform operations on data values. They are
categorized as follows:

 Arithmetic Operators: Perform mathematical operations.

let sum = 5 + 3; // Addition


let difference = 5 - 3; // Subtraction
let product = 5 * 3; // Multiplication
let quotient = 5 / 3; // Division
let remainder = 5 % 3; // Modulus

 Comparison Operators: Compare values and return a boolean result.

let isEqual = 5 == "5"; // true (loose equality)


let isStrictEqual = 5 === "5"; // false (strict equality)
let isGreater = 5 > 3; // true

 Logical Operators: Combine or invert boolean expressions.

let result = (5 > 3) && (3 < 4); // true (AND)


let result2 = (5 > 3) || (3 > 4); // true (OR)
let result3 = !(5 > 3); // false (NOT)

 Assignment Operators: Assign or update values of variables.

let x = 10;
x += 5; // Equivalent to x = x + 5;
x *= 2; // Equivalent to x = x * 2;

Conditional Statements:
Conditional statements allow you to perform actions based on conditions. Common statements
include:
 if Statement: Executes a block of code if a condition is true.

if (age > 18) {


console.log("Adult");
}

 if-else Statement: Provides an alternative block if the condition is false.

if (age > 18) {


console.log("Adult");
} else {
console.log("Minor");
}

 else if Statement: Evaluates multiple conditions.

if (age < 13) {


console.log("Child");
} else if (age < 20) {
console.log("Teenager");
} else {
console.log("Adult");
}

 switch Statement: Handles multiple conditions with different cases.

let fruit = "apple";


switch (fruit) {
case "apple":
console.log("Apple is red.");
break;
case "banana":
console.log("Banana is yellow.");
break;
default:
console.log("Unknown fruit.");
}

JavaScript Loops:
Loops are used to execute a block of code repeatedly:

 for Loop: Executes a block of code a specific number of times.


for (let i = 0; i < 5; i++) {
console.log(i);
}

 while Loop: Executes a block of code as long as a condition is true.

let i = 0;
while (i < 5) {
console.log(i);
i++;
}

 do-while Loop: Executes a block of code at least once, then repeats while the condition is
true.

let i = 0;
do {
console.log(i);
i++;
} while (i < 5);

 for-in Loop: Iterates over the properties of an object.

let person = {name: "Alice", age: 25};


for (let key in person) {
console.log(key + ": " + person[key]);
}

 for-of Loop: Iterates over the values of an iterable object, such as an array.

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


for (let color of colors) {
console.log(color);
}

JavaScript Break and Continue Statements


Break and continue statements are used to control the flow of loops.

 Break Statement: Terminates the current loop or switch statement prematurely.

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


if (i === 5) {
break; // Exits the loop when i is 5
}
console.log(i);
}

 Continue Statement: Skips the current iteration and moves to the next iteration of the loop.

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


if (i === 5) {
continue; // Skips the rest of the loop body when i is 5
}
console.log(i);
}

Use Cases:
Break is useful when you want to exit a loop early based on a specific condition.
Continue is helpful when you want to skip certain iterations but keep looping through the rest.
Example with Nested Loops

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


for (let j = 0; j < 3; j++) {
if (i === j) {
continue; // Skips when i equals j
}
console.log(`i = ${i}, j = ${j}`);
}
}

Dialog Boxes in JavaScript:


Dialog boxes are used to interact with users in JavaScript. There are three common types:

 Alert Box (alert): Displays a message to the user and has an OK button.

alert("This is an alert box!");

 Confirm Box (confirm): Displays a dialog box with OK and Cancel buttons. It returns true
if the user clicks OK, and false if they click Cancel.

let userConfirmed = confirm("Do you want to proceed?");


if (userConfirmed) {
alert("You clicked OK.");
} else {
alert("You clicked Cancel.");
}
 Prompt Box (prompt): Displays a dialog box that asks the user to enter some input. It
returns the input as a string, or null if the user presses Cancel.

let userInput = prompt("Please enter your name:");


if (userInput != null) {
alert("Hello " + userInput + "!");
}

JavaScript Arrays:
Arrays in JavaScript are used to store multiple values in a single variable. They can hold values
of any data type.

 Declaring an Array:

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


Accessing Array Elements: Arrays are zero-indexed, so you can access elements using their
index.

let firstFruit = fruits[0]; // "Apple"

Array Methods:
push(): Adds an element to the end of an array.
fruits.push("Orange");

pop(): Removes the last element from an array.


fruits.pop();

shift(): Removes the first element from an array.


fruits.shift();

unshift(): Adds an element to the beginning of an array.


fruits.unshift("Mango");

forEach(): Executes a function on each array element.


fruits.forEach(function(fruit) {
console.log(fruit);
});

JavaScript User-Defined Functions:


A function is a block of code designed to perform a particular task. You can define your own
functions in JavaScript.
 Function Declaration:

function greet(name) {
return "Hello " + name + "!";
}

 Calling the Function:

let message = greet("Alice");


alert(message); // "Hello Alice!"

 Function Expression: Functions can also be defined as expressions, assigned to variables.

let sum = function(a, b) {


return a + b;
};
alert(sum(5, 10)); // 15

 Arrow Functions: JavaScript also supports arrow functions, which are a more concise way
to write functions.

const multiply = (a, b) => a * b;


alert(multiply(3, 4)); // 12

String Built-in Functions:


Strings in JavaScript come with various built-in methods for manipulation:

 charAt(): Returns the character at a specific index.

let str = "Hello";


console.log(str.charAt(1)); // "e"
concat(): Combines two or more strings.

let str1 = "Hello";


let str2 = " World";
console.log(str1.concat(str2)); // "Hello World"

 indexOf(): Returns the index of the first occurrence of a specified value.

let str = "Hello World";


console.log(str.indexOf("World")); // 6

 toUpperCase(): Converts a string to uppercase.


let str = "hello";
console.log(str.toUpperCase()); // "HELLO"

 toLowerCase(): Converts a string to lowercase.

let str = "HELLO";


console.log(str.toLowerCase()); // "hello"

substring(): Extracts a portion of a string.

let str = "Hello World";


console.log(str.substring(0, 5)); // "Hello"

replace(): Replaces part of a string with another string.

let str = "Hello World";


console.log(str.replace("World", "JavaScript")); // "Hello JavaScript"

Math Built-in Functions:


Math in JavaScript provides various mathematical operations and constants:

Math.abs(): Returns the absolute value of a number.

console.log(Math.abs(-5)); // 5

Math.round(): Rounds a number to the nearest integer.

console.log(Math.round(4.5)); // 5

Math.floor(): Rounds a number down to the nearest integer.

console.log(Math.floor(4.9)); // 4

Math.ceil(): Rounds a number up to the nearest integer.

console.log(Math.ceil(4.1)); // 5

Math.random(): Returns a random number between 0 (inclusive) and 1 (exclusive).

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

Math.max(): Returns the largest of the numbers.

console.log(Math.max(10, 20, 30)); // 30


Math.min(): Returns the smallest of the numbers.

console.log(Math.min(10, 20, 30)); // 10

Math.pow(): Returns the base to the exponent power.

console.log(Math.pow(2, 3)); // 8

Array Built-in Functions:


Arrays in JavaScript have many methods for manipulation:

push(): Adds one or more elements to the end of an array.

let arr = [1, 2, 3];


arr.push(4);
console.log(arr); // [1, 2, 3, 4]

pop(): Removes the last element from an array.

let arr = [1, 2, 3];


arr.pop();
console.log(arr); // [1, 2]

shift(): Removes the first element from an array.

let arr = [1, 2, 3];


arr.shift();
console.log(arr); // [2, 3]

unshift(): Adds one or more elements to the beginning of an array.

let arr = [2, 3];


arr.unshift(1);
console.log(arr); // [1, 2, 3]

concat(): Combines two or more arrays.

let arr1 = [1, 2];


let arr2 = [3, 4];
let combined = arr1.concat(arr2);
console.log(combined); // [1, 2, 3, 4]

map(): Creates a new array with the results of calling a provided function on every element.
let arr = [1, 2, 3];
let doubled = arr.map(num => num * 2);
console.log(doubled); // [2, 4, 6]

filter(): Creates a new array with all elements that pass the test.

let arr = [1, 2, 3, 4];


let even = arr.filter(num => num % 2 === 0);
console.log(even); // [2, 4]

forEach(): Executes a function for each element of the array.

let arr = [1, 2, 3];


arr.forEach(num => console.log(num));
// 1
// 2
// 3

Date Built-in Functions:


JavaScript provides the Date object to handle dates and times:

new Date(): Creates a new Date object with the current date and time.

let date = new Date();


console.log(date); // Current date and time

getDate(): Returns the day of the month (1-31).

let date = new Date();


console.log(date.getDate()); // Day of the month

getDay(): Returns the day of the week (0-6, where 0 is Sunday).

let date = new Date();


console.log(date.getDay()); // Day of the week

getMonth(): Returns the month (0-11, where 0 is January).

let date = new Date();


console.log(date.getMonth()); // Month (0-11)
getFullYear(): Returns the four-digit year.

let date = new Date();


console.log(date.getFullYear()); // Year (e.g., 2024)

setFullYear(): Sets the year of the Date object.

let date = new Date();


date.setFullYear(2025);
console.log(date); // Updated date with the new year

toLocaleString(): Returns a string representing the date, based on the locale.

let date = new Date();


console.log(date.toLocaleString()); // e.g., "12/14/2024, 12:34:56 PM"

getTime(): Returns the timestamp (milliseconds since January 1, 1970).

let date = new Date();


console.log(date.getTime()); // Timestamp

Events:

Mouse Events:
onclick
Triggered when an element is clicked.
Example:
<button onclick="alert('Button clicked!')">Click Me</button>

ondblclick
Triggered when an element is double-clicked.
Example:
<button ondblclick="alert('Button double-clicked!')">Double Click Me</button>

onmouseover
Triggered when the mouse pointer hovers over an element.
Example:
<p onmouseover="this.style.color='red'">Hover over me!</p>

onmouseout
Triggered when the mouse pointer leaves an element.
Example:
<p onmouseout="this.style.color='black'">Mouse out!</p>
Keyboard Events:
onkeypress
Triggered when a key is pressed (excluding some special keys).
Example:
<input onkeypress="alert('Key pressed!')" />

onkeyup
Triggered when a key is released.
Example:
<input onkeyup="console.log('Key released')" />

Form and Focus Events:


onfocus
Triggered when an element gains focus (e.g., clicking into an input field).
Example:
<input onfocus="this.style.backgroundColor='lightblue'" />

onblur
Triggered when an element loses focus.
Example:
<input onblur="this.style.backgroundColor='white'" />

onchange
Triggered when the value of an element (like a text field or dropdown) changes.
Example:
<select onchange="alert('Selection changed!')">
<option>Option 1</option>
<option>Option 2</option>
</select>

onsubmit
Triggered when a form is submitted.
Example:
<form onsubmit="alert('Form submitted!'); return false;">
<input type="text" />
<button type="submit">Submit</button>
</form>

onreset
Triggered when a form is reset.
Example:
<form onreset="alert('Form reset!')">
<input type="text" />
<button type="reset">Reset</button>
</form>

Window Events:
onload
Triggered when the page or an element (e.g., an image) has fully loaded.
Example:
<body onload="alert('Page loaded!')">

DOM (Document Object Model)


The DOM is a programming interface for web documents. It represents the structure of a
document as a tree of objects, allowing developers to manipulate its content, structure, and
styling.

Key Features:
Accessing Elements: Use JavaScript to access and manipulate HTML elements.

document.getElementById("elementId"); // Access an element by ID


document.querySelector(".className"); // Access an element by class or CSS selector

Creating Elements:

let newDiv = document.createElement("div"); // Create a new div element


newDiv.textContent = "Hello World!"; // Add content
document.body.appendChild(newDiv); // Append it to the DOM

Event Listeners: Add interactivity.

document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});

Manipulating Styles:

let element = document.getElementById("elementId");


element.style.color = "blue";

History Object
The history object allows developers to manipulate the browser's session history. It is part of the
window object.

Key Methods:
history.back(): Navigates to the previous page.

history.back();
history.forward(): Navigates to the next page.

history.forward();

history.go(n): Navigates to a specific position (n) in the history stack.

history.go(-1); // Moves one step back


history.go(2); // Moves two steps forward

history.pushState(): Adds a new entry to the session history without reloading the page.

history.pushState({ page: 1 }, "Title", "/new-page");

Form Validation & Email Validation


Form Validation
Form validation ensures that user inputs meet certain criteria before submission. It can be done
using both HTML5 and JavaScript.

Example:
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" required minlength="3">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
let username = document.getElementById("username").value;
if (username.length < 3) {
alert("Username must be at least 3 characters long.");
event.preventDefault(); // Prevent form submission
}
});
</script>

Email Validation
Email validation ensures that the entered email address is in a valid format.

HTML5 Email Validation:


<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<button type="submit">Submit</button>
</form>
JavaScript Email Validation:
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}

document.getElementById("email").addEventListener("input", function() {
const email = this.value;
if (!validateEmail(email)) {
this.style.borderColor = "red";
} else {
this.style.borderColor = "green";
}
});

You might also like