Java Script

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

JavaScript -Krishnan

0. Overview:

JavaScript is a versatile programming language primarily used for front-end web development, but it has
expanded its reach to various other domains, including server-side development (Node.js), mobile app development,
and even desktop applications. Here's an overview of JavaScript:

1. Purpose and Usage:

• JavaScript was initially created to add interactivity and dynamic behaviour to web pages.

• It is commonly used for client-side scripting to enhance user interfaces and respond to user actions
on websites.

2. Execution Environment:

• JavaScript is primarily executed by web browsers, allowing developers to create interactive and
dynamic content on the client side.

• With the introduction of Node.js, JavaScript can also be used for server-side development,
enabling full-stack development using a single language.

3. Syntax:

• JavaScript syntax is similar to other C-style languages like Java and C++, making it relatively easy
for developers to learn if they are familiar with these languages. Codes will be give inside a <script>
tag or as separate script file.

• It is an interpreted language, and the source code is executed by the JavaScript engine in the
browser or server environment.

4. Data Types:

• JavaScript supports various data types, including numbers, strings, booleans, objects, arrays, and
functions.

5. Dynamic Typing:

• JavaScript is dynamically typed, meaning that variable types are determined at runtime. This
provides flexibility but requires careful handling to avoid unexpected behaviour.
6. Functions:

• Functions are a fundamental part of JavaScript. They can be defined, assigned to variables, passed
as arguments, and returned as values.

7. Event-Driven Programming:

• JavaScript is often used in an event-driven paradigm, where actions or events trigger specific
functions or behaviours. This is crucial for creating interactive web pages.

8. DOM Manipulation:

• The Document Object Model (DOM) is a programming interface for web documents. JavaScript is
commonly used to manipulate the DOM, enabling dynamic changes to the structure and content
of web pages.

9. Asynchronous Programming:

• JavaScript uses an asynchronous, non-blocking execution model. This is essential for handling tasks
like AJAX requests, animations, and other operations that should not block the main thread.

10. Libraries and Frameworks:

• There are numerous libraries and frameworks built on top of JavaScript, such as jQuery, React,
Angular, and Vue.js, which simplify and streamline web development tasks.

11. ES6 and Beyond:

• ECMAScript 6 (ES6) introduced significant improvements to the language, including arrow


functions, classes, template literals, and destructuring. Subsequent versions of ECMAScript
continue to enhance JavaScript's capabilities.

1. What is a variable in JavaScript?

In JavaScript, a variable is a container for storing data values. Variables are used to store and manipulate
information in a program. You can think of a variable as a named storage location that holds a value, and this value can
be changed during the execution of a program.

2. Creating Variables using var, let, const:

In JavaScript, there are three ways to declare variables: var, let, and const.

• var: This was the original way to declare variables in JavaScript, but it has some issues and is now less
commonly used. Variables declared with var are function-scoped, which means they are only available
within the function where they are declared.
var x = 10;

• let: Introduced in ECMAScript 6 (ES6), let allows you to declare block-scoped variables. Block-scoped
means the variable is only available within the block (a pair of curly braces) where it is defined.
let y = 20;

• const: Also introduced in ES6, const is used to declare constants. Once a value is assigned to a const
variable, it cannot be reassigned. However, it's important to note that the constantans applies to the
reference in case of objects and arrays, not the value.

const z = 30;
3. Printing values of variables:-

We can use addition( + ) operator to print variables along with strings.

<script>
let name = "Krishnan";
let age = 25;

// Using string concatenation


let message = "Hello, my name is " + name + " and I am " + age + " years old.";
console.log(message);
</script>

We can use template literals to print variables along with strings.

Syntax → `${var_name}`
<script>
let name = "Krishnan";
let age = 25;

// Using string concatenation


let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);
</script>

4. HTML example code for all types of values and print using document.write()

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JavaScript Variables Example</title>
</head>
<body>

<script>
// Using var
var a = “hello”;
document.write(a);

// Using let
let b = ‘a’;
document.write(b);

// Using const
const pi = 3.14;
document.write("<br>" + c);
</script>

</body>
</html>

All these variables can all type of data like integer, float, character, string, JSON.
5.Operators

In programming, an operator is a symbol or keyword that performs operations on one or more operands.
Operators are used to manipulate data and variables in expressions or statements.

The operands can be values, variables, or expressions themselves. The type of operation an operator performs
depends on its functionality and the types of operands it operates on.

5.i) Arithmetic Operators:

Arithmetic operators perform basic arithmetic operations like addition, subtraction, multiplication,
division, and more.

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arithmetic Operators</title>
</head>
<body>
<script>
var num1 = 10;
var num2 = 5;

document.write("Addition: " + (num1 + num2) + "<br>");


document.write("Subtraction: " + (num1 - num2) + "<br>");
document.write("Multiplication: " + (num1 * num2) + "<br>");
document.write("Division: " + (num1 / num2) + "<br>");
document.write("Modulus: " + (num1 % num2) + "<br>");
</script>
</body>
</html>

5.ii) Comparison Operators:

Comparison operators compare values and return a Boolean result (true or false).
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comparison Operators</title>
</head>
<body>
<script>
var num1 = 10;
var num2 = 5;

document.write("Equal to: " + (num1 == num2) + "<br>");


document.write("Not equal to: " + (num1 != num2) + "<br>");
document.write("Greater than: " + (num1 > num2) + "<br>");
document.write("Less than: " + (num1 < num2) + "<br>");
document.write("Greater than or equal to: " + (num1 >= num2) + "<br>");
document.write("Less than or equal to: " + (num1 <= num2) + "<br>");
</script>
</body>
</html>
5.iii) Logical Operators:

Logical operators perform logical operations and return a Boolean result (true or false).

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logical Operators</title>
</head>
<body>
<script>
var condition1 = true;
var condition2 = false;

document.write("AND: " + (condition1 && condition2) + "<br>");


document.write("OR: " + (condition1 || condition2) + "<br>");
document.write("NOT: " + (!condition1) + "<br>");
</script>
</body>
</html>
5.iv) Assignment Operators:

Assignment operators assign values to variables.

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Assignment Operators</title>
</head>
<body>
<script>
var x = 5;
document.write("Original value of x: " + x + "<br>");

// Assign new values using various assignment operators


x += 3; // Equivalent to x = x + 3;
document.write("After +=: " + x + "<br>");

x -= 2; // Equivalent to x = x - 2;
document.write("After -=: " + x + "<br>");

x *= 4; // Equivalent to x = x * 4;
document.write("After *=: " + x + "<br>");

x /= 2; // Equivalent to x = x / 2;
document.write("After /=: " + x + "<br>");
</script>
</body>
</html>
6.Conditional Statements

Conditional statements in JavaScript are used to make decisions in your code based on certain conditions.
These statements allow your program to execute different blocks of code depending on whether a specified condition
evaluates to true or false. There are several types of conditional statements in JavaScript:

1. if statement:

• The if statement is a basic conditional statement that executes a block of code if a specified condition
is true.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>if Statement</title>
</head>
<body>
<script>
// JavaScript code
let num = 10;

if (num > 0) {
document.write("The number is positive");
}
</script>
</body>
</html>

2. if-else statement:

• The if-else statement allows you to specify a block of code to be executed if the condition is true and
another block if the condition is false.

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>if-else Statement</title>
</head>
<body>
<script>
// JavaScript code
let num = -5;

if (num > 0) {
document.write("The number is positive");
}
else {
document.write("The number is not positive");
}
</script>
</body>
</html>
3. if-else if-else statement:

• The if-else if-else statement allows you to check multiple conditions and execute different blocks of
code based on the first true condition.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>if-else if-else Statement</title>
</head>
<body>
<script>
// JavaScript code
let num = 0;

if (num > 0) {
document.write("The number is positive");
}
else if (num < 0) {
document.write("The number is negative");
}
else {
document.write("The number is zero");
}
</script>
</body>
</html>
4. switch statement:

• The switch statement is used to perform different actions based on different conditions.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>switch Statement</title>
</head>
<body>
<script>
// JavaScript code
let day = "Wednesday"; // Change this to any day of the week

switch (day) {
case "Monday":
document.write("It's the start of the week");
break;
case "Tuesday":
document.write("It's a weekday");
break;
case "Wednesday":
document.write("It's the middle of the week");
break;
case "Thursday":
document.write("It's almost the weekend");
break;
case "Friday":
document.write("It's the end of the week");
break;
case "Saturday":
document.write("It's the weekend");
break;
case "Sunday":
document.write("It's the weekend");
break;
default:
document.write("Invalid day");
}
</script>
</body>
</html>

These examples showcase the use of different conditional statements in JavaScript, each with its specific
purpose. You can embed these JavaScript code snippets in your HTML files to see them in action.
7.Loops

In programming, a loop is a control structure that allows a set of instructions to be repeated multiple times.
Loops are used when you want to execute a block of code repeatedly until a certain condition is met. They help in
automating repetitive tasks and make code more concise.

1. For Loop:

• A for loop is used to execute a block of code a specified number of times.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>For Loop Example</title>
</head>
<body>
<script>
for (let i = 1; i <= 5; i++) {
document.write('Iteration ' + i);
}
</script>
</body>
</html>

2. While Loop:

• A while loop is used to execute a block of code as long as the specified condition is true.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>While Loop Example</title>
</head>
<body>
<script>
let i = 1;
while (i <= 5) {
document.write('Iteration ' + i);
i++;
}
</script>
</body>
</html>
3. Do...While Loop:

• A do...while loop is similar to a while loop, but the block of code is executed at least once, even if
the condition is false.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Do...While Loop Example</title>
</head>
<body>
<script>
let i = 1;
do {
document.write('Iteration ' + i);
i++;
} while (i <= 5);
</script>
</body>
</html>

8.Functions

8.i) What are functions?

In JavaScript, a function is a reusable block of code that performs a specific task. Functions help in
organizing code, making it more modular and easier to maintain. Functions can take parameters (input values),
perform operations, and return a result.

8.ii) Creating Functions:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Function</title>
</head>
<body>
<script>
// Creating a simple function
function askUser() {
document.write("Hey Who are you😁..?");
}

// Calling the function


askUser();
</script>
</body>
</html>
8.iii) Creating Functions with Parameters:

Functions can accept parameters, which are variables that hold values passed to the function

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function with Parameters</title>
</head>
<body>
<script>
// Creating a function with parameters
function greet(name) {
console.log("Hello, " + name + "!");
}
// Calling the function with a parameter
greet("John");
</script>
</body>
</html>

9.DOM (Document Object Model):

The Document Object Model (DOM) is a programming interface for web documents. It represents the
structure of a document as a tree-like model where each node corresponds to a part of the document. The DOM
provides a way for scripts to dynamically access, manipulate, and update the content, structure, and style of a
document. Usages of JavaScript as follows,

1. Accessing HTML Elements:

• Retrieve and reference HTML elements in a document using JavaScript.

2. Manipulating HTML Elements:

• Create, modify, or delete HTML elements dynamically during runtime.

3. Handling Events:

• Attach event listeners to respond to user interactions (e.g., clicks, key presses, form submissions).

4. Dynamic Styling:

• Change the styles (e.g., color, size, visibility) of HTML elements dynamically.

5. Modifying Document Structure:

• Add or remove elements, change their hierarchy, and manipulate the overall structure of the
document.

6. Dynamic Content Updates:

• Update the content of a webpage dynamically without requiring a full-page refresh.

7. Traversal and Navigation:

• Navigate through the document tree, moving from one element to another, and accessing parent,
child, or sibling elements.

8. Forms and User Input Handling:

• Access and manipulate form elements, validate user input, and handle form submissions.
9.i).Changing element content and inline CSS style using JS DOM method

<!DOCTYPE html>
<html>
<head>
<title>1</title>
</head>
<body>
<p id="p1">i'm a paragraph tag</p>
<button onmouseout="dothat()">Hit Me</button>

<script type="text/javascript">
let ele = document.getElementById("p1");

function dothat(){
ele.style.backgroundColor="green";
ele.style.fontSize="100px";
ele.style.color="white";
ele.style.border="3px dotted blue";
ele.innerText="Content Changed";
}
</script>
</body>
</html>

Explanation

1. HTML Snippet

• Type HTML basic structure

2. Insert a paragraph tag:

• Create a paragraph with the id "p1" containing the text "I'm a paragraph tag"

(<p id="p1">i'm a paragraph tag</p>)

3. Insert a button with an onmouseout event:

• Create a button with the text "Hit Me" and an onmouseou event that triggers the dothat function
(<button onmouseout="dothat()">Hit Me</button>)

4. Write the JavaScript code:

• Open a script tag (<script type="text/javascript">)

• Get the element with the id "p1" (let ele = document.getElementById("p1");)

• Define the dothat function:

• Change the background color of the paragraph to green.

• Set the font size to 100 pixels.

• Change the text color to white.

• Add a 3-pixel dotted blue border.

• Change the text content to "Content Changed".

• Close the script tag (</script>).


9.ii).Modyfying attributes using JS DOM methods

<!DOCTYPE html>
<html>
<head>
<title>Change Attribute</title>
</head>
<body>
<img id="myImage" src="smiley.gif">
<button onclick="changeImage()">Change image</button>
<script>
function changeImage() {
var image = document.getElementById("myImage");
image.setAttribute("src", "landscape.jpg");
image.setAttribute("height", "500px");
image.setAttribute("width", "500px");
}
</script>
</body>
</html>

Explanations: -

1. HTML Snippet

• Type HTML basic structure

2. Insert an image element with an id and a src attribute:

• Create an image with the id "myImage" and the initial source "smiley.gif"
(<img id="myImage" src="smiley.gif">)

3. Insert a button with an onclick event:

• Create a button with the text "Change image" and an onclick event that triggers the changeImage
function
(<button onclick="changeImage()">Change image</button>).

4. Write the JavaScript code:

• Open a script tag (<script>).

• Define the changeImage function:

• Get the image element by its id.

• Use the setAttribute method to change the src attribute value to "landscape.jpg".

• Close the script tag (</script>).


9.iii).Accesing form input values in JS

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- Input fields for Name and Age -->
<label>Enter Name</label>
<input type="text" id="fn">
<label>Enter Age</label>
<input type="number" id="age">

<!-- Button to trigger the show function -->


<input type="button" onclick="show()" value="Click">

<!-- Display area for the result -->


<p id="target"></p>

<!-- JavaScript code -->


<script>
// Step 1: Create varibles to handle HTML elements
let name = document.getElementById("fn");
let age = document.getElementById("age");
let ptag = document.getElementById("target");

// Step 2: Define the show function


function show(){
// Step 3: Assign value of input tag to p tag textContent
ptag.textContent = name.value + age.value;
}
</script>
</body>
</html>
9.iv). Creating elements using JS

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Element Example</title>
</head>
<body>
<h1>Create Element Example</h1>

<button onclick="createElement1()">Create Element</button>

<div id="output">

</div>

<script>
var outputDiv = document.getElementById("output");
function createElement1() {
var paragraph = document.createElement("p");
paragraph.textContent = "This is a dynamically created paragraph.";
outputDiv.appendChild(paragraph);
}
</script>
</body>
</html>

Algorithm:-

1. HTML Structure:

• Create the basic HTML template.

2. Page Content:

• <h1>Create Element Example</h1>: Adds a heading to the page.

• <button onclick="createElement1()">Create Element</button>: Creates a button that, when clicked,


calls the createElement1 function.

• <div id="output"></div>: Provides a container with the id "output" where the dynamically created
paragraph will be appended.

3. JavaScript Code:

• <script>: Contains JavaScript code that enhances the functionality of the page.

• var outputDiv = document.getElementById("output");: Retrieves the div with the id "output."

• function createElement1() { ... }: Defines the createElement1 function.

• var paragraph = document.createElement("p");: Creates a new paragraph element.

• paragraph.textContent = "This is a dynamically created paragraph.";: Sets the text content of the
paragraph.

• outputDiv.appendChild(paragraph);: Appends the newly created paragraph to the "output" div.


Mini Project 1 – Creating a Simple To-Do List

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>To-Do’s</title>
<style>
//Add CSS here
</style>
</head>
<body>
<h2>To-Do List Using Unordered List</h2>
<input type="text" id="task">
<button onclick="add()">Add Task</button>
<ul id="list"></ul>
<script>
let parent = document.getElementById('list');

function add() {
// Step 1: Retrieve the task input element
let taskInput = document.getElementById('task');

// Step 2: Create a new list item


let listItem = document.createElement('li');

// Step 3: Set the text content of the list item


listItem.textContent = taskInput.value;

// Step 4: Create a "Task Finished" button


let finishButton = document.createElement('button');
finishButton.textContent = "Task Finished";

// Step 5: Attach an onclick event to the button


finishButton.onclick = function () {
listItem.style.textDecoration = "line-through";
};

// Step 6: Append the button to the list item


listItem.appendChild(finishButton);

// Step 7: Append the list item to the unordered list


parent.appendChild(listItem);
}

</script>
</body>
</html>
10. querySelector() and querySelectorAll()

• querySelector():

• querySelector() is a method in JavaScript that allows you to select the first element in the document
that matches a specified CSS selector.

• It returns the first matching element or null if no element is found.

• Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>querySelector</title>
</head>
<body>
<p id="para"></p>
<script>
const element = document.querySelector('#para');
element.innerText = "Hello";
</script>
</body>
</html>

• Explanation:-

1. Initialize HTML Document:

• Create a basic html template.

2. Create a Paragraph Element:

• Within the <body> section, create a <p> element with the id attribute set to "para."

3. JavaScript Code Block:

• Add a <script> tag within the <body> section to contain JavaScript code.

4. Select Element with querySelector:

• Use document.querySelector('#para') to select the paragraph element with the ID


"para."

• Store the reference to the selected element in the variable element.

5. Modify Text Content:

• Use element.innerText = "Hello" to set the text content of the selected paragraph to
"Hello."
• querySelectorAll():

• querySelectorAll() is similar to querySelector() but returns a NodeList containing all elements that
match the specified CSS selector.

• It returns an empty NodeList if no elements are found.

• Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>querySelectorAll</title>
</head>
<body>
<p class="para"></p>
<p class="para"></p>
<p class="para"></p>
<p class="para"></p>
<script>
const elements = document.querySelectorAll('.para');
for (let i = 0; i < elements.length; i++) {
elements[i].innerText = "Hello " + i;
}
</script>
</body>
</html>

• Explanation:

1. Set Character Encoding and Title:

• Include a <meta> tag within the <head> section to set the character encoding (UTF-
8).

• Set the document title using the <title> tag.

2. Create Paragraph Elements:

• Within the <body> section, create four <p> elements with the class "para."

3. JavaScript Code Block:

• Add a <script> tag within the <body> section to contain JavaScript code.

4. Select Elements with querySelectorAll:

• Use document.querySelectorAll('.para') to select all paragraphs with the class


"para."

• Store the NodeList of selected elements in the variable elements.

5. Iterate Through Elements and Modify Text Content:

• Use a for loop to iterate through each element in the NodeList:

• For each iteration, set the innerText of the current element to "Hello "
followed by the loop index (i).
10.ii) Why Use querySelector() and querySelectorAll()?

• Simplicity and Readability:

• These methods provide a concise and readable way to select elements from the DOM using CSS
selectors, making the code more expressive and maintainable.

• Powerful Selectors:

• CSS selectors are powerful and flexible, allowing for complex queries based on element
attributes, relationships, and more.

• Single and Multiple Element Selection:

• querySelector() is used when you only need the first matching element, while querySelectorAll()
is useful for selecting multiple elements.

10.iii) Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiple querySelector</title>
<style>
.highlight {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div id="container">
<p class="highlight">This paragraph is highlighted.</p>
<p>This paragraph is not highlighted.</p>
<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
</div>

<script>
// Selecting by ID
const container = document.querySelector('#container');
container.style.border = '2px solid blue';

// Selecting by class
const hlPar = document.querySelector('.highlight');
hlPar.textContent = 'Now I am modified!';

// Selecting by tag name


const listItems = document.querySelectorAll('li');
for (let i = 0; i < listItems.length; i++) {
listItems[i].textContent = `Modified Item ${i + 1}`;
listItems[i].style.color = "rgb(57,120,200)";
}
</script>
</body>
</html>
11.setTimeout

setTimeout is a JavaScript function that allows you to schedule the execution of a function after a specified
delay in milliseconds. It is commonly used to introduce a delay before executing a particular piece of code or to create
timed intervals.

Example :-

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>setTimeout Example</title>
</head>
<body>
<h2>setTimeout in JS</h2>
<p id="message"></p>

<script>
// Function to be executed after a delay
function showMessage() {
let p = document.getElementById('message');
p.innerText = 'Hello, this message was delayed! for 3 seconds';
}

// Using setTimeout to show Message after 3000 milliseconds (3


seconds)
setTimeout(showMessage, 4000);
</script>
</body>
</html>

Explantion :-

1. The HTML document contains an <h2> heading and a <p> element with the id "message," where the delayed
message will be displayed.
2. The JavaScript code includes a showMessage function that updates the text content of the "message" element.
3. The setTimeout function is then used to schedule the execution of the showMessage function after a delay of
3000 milliseconds (3 seconds).
4. When the page loads, the message will not appear immediately. After the specified delay, the showMessage
function will be executed, updating the content of the "message" element, and the delayed message will be
displayed.
12.Array’s In JS

In JavaScript, an array is a data structure that allows you to store and manipulate a collection of values. Arrays
can hold various types of data, including numbers, strings, objects, and even other arrays. They provide a way to
organize and access elements using numerical indices.

Here are some key concepts related to arrays in JavaScript:

1. Declaration and Initialization:

• You can create an array using the array literal notation [].

• Examples:

<script>
// Using []
let fruits = ['Apple', 'Banana', 'Orange'];
</script>

2. Accessing Elements:

• Array elements are accessed using their index, starting from 0.

• Example:

<script>
let fruits = ['Apple', 'Banana', 'Orange'];
console.log(fruits[0]); // Output: apple
</script>
3. Array Length:

• The length property returns the number of elements in an array.

• Example:

<script>
let fruits = ['Apple', 'Banana', 'Orange'];
console.log(fruits.length); // Output: 3
</script>
4. Array Methods
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Array Methods</title>
</head>
<body>
<h1>JavaScript Array Methods Example</h1>
<script>
// Sample array
let originalArray = [1, 2, 3, 4, 5];

// Display the original array


console.log("Original Array:", originalArray);

// 1. push(): Adds elements to the end of an array


originalArray.push(6, 7);
console.log("After push():", originalArray);

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


originalArray.pop();
console.log("After pop():", originalArray);

// 3. unshift(): Adds elements to the beginning of an array


originalArray.unshift(0);
console.log("After unshift():", originalArray);

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


originalArray.shift();
console.log("After shift():", originalArray);

// 5. slice(): Extracts a portion of an array


let slicedArray = originalArray.slice(1, 3);
console.log("Sliced Array:", slicedArray);

// 6. splice(): Changes the contents of an array by removing or replacing existing elements


originalArray.splice(1, 2, 10, 11);
console.log("After splice():", originalArray);

// 7. concat(): Merges two or more arrays


let newArray = originalArray.concat([8, 9]);
console.log("Concatenated Array:", newArray);

// 8. indexOf(): Returns the first index at which a given element can be found in the array
let indexOfElement = originalArray.indexOf(10);
console.log("Index of 10:", indexOfElement);

// 9. includes(): Checks if an array includes a certain element


let includesElement = originalArray.includes(5);
console.log("Includes 5:", includesElement);

// 10. map():creates a new array by applying a operation to each values

let mappedArray = originalArray.map(x => x * 2);


console.log("Mapped Array:", mappedArray);

// 11. filter(): filters values based on condition

let filteredArray = originalArray.filter(x => x > 5);


console.log("Filtered Array:", filteredArray);

// 12. forEach(): Calls a function for each element in the array


originalArray.forEach(element => console.log("forEach Element:", element));
</script>
</body>
</html>
12.ii) Changing Background Color Using JS with Arrays:-

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Changing Color</title>
</head>
<body>
<button onclick="change()">Change Background Color</button>
<script>
let color = ["red","blue","green","lightgreen"];
function change(){
let ind = Math.floor(Math.random()*3);
document.body.style.backgroundColor=color[ind];
}
</script>
</body>
</html>

Explanation:-

1. HTML Structure:

• Create a html template

2. Button and Script Section:

• <button onclick="change()">Change Background Color</button>: Creates a button that


triggers the change function when clicked.

• <script>: Contains JavaScript code.

• let color = ["red", "blue", "green", "lightgreen"];: Defines an array named color containing
four different color strings.

• function change() { ... }: Defines a JavaScript function named change. This function is called
when the button is clicked.

• let ind = Math.floor(Math.random() * 4);: Generates a random integer between 0 and 3


(inclusive) and assigns it to the variable ind.

• document.body.style.backgroundColor = color[ind];: Sets the background color of the body


element to the color at index ind in the color array.

3. Random Color Selection:

• The change function generates a random index (ind) and uses it to select a color from the color
array.

• The selected color is then applied as the background color of the body element.
12.ii) Load Multiple images using Array with setTimeout

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Loading Multiple Images using array</title>
</head>
<body>
<img height="300px" width="300px" id="ig">
<script type="text/javascript">
let paths=["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"];
let init = 0;
function loadimg(){
let i = document.getElementById('ig');
if(init < paths.length){
i.setAttribute("src",paths[init]);
init++;
setTimeout(loadimg,1000);
}
}
loadimg()
</script>
</body>
</html>
1. HTML Structure:

• Create an html template

2. Header and Image Loading Section:

• <h1>Loading Multiple Images using array</h1>: Displays a heading indicating the purpose of the
page.

• <img height="300px" width="300px" id="ig">: Defines an image element with an initial height and
width, and an id of 'ig'.

3. JavaScript Section:

• <script type="text/javascript">: Begins a JavaScript script block.

• let paths = [...]: Defines an array named paths containing file paths to multiple images.

• let init = 0;: Initializes a variable init to keep track of the current image being loaded.

• function loadimg() { ... }: Defines a JavaScript function named loadimg.

• let i = document.getElementById('ig');: Retrieves the image element by its id.

• if (init < paths.length) { ... }: Checks if there are more images to load.

• i.setAttribute("src", paths[init]);: Sets the source attribute of the image element to the path
of the current image.

• init++;: Increments the init variable to move to the next image in the array.

• setTimeout(loadimg, 1000);: Sets a timeout of 1000 milliseconds (1 second) before loading


the next image.

• loadimg(): Calls the loadimg function to start loading the images when the page loads.
13. Date Object in JavaScript

The Date object in JavaScript is used for working with dates and times. It provides methods to get and set
various date and time components, such as the year, month, day, hour, minute, second, and milliseconds. The Date
object is particularly useful for handling operations involving dates, such as calculating durations, formatting dates
for display, and working with time intervals.

Methods in the Date object;

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Object Methods</title>
</head>
<body>
<h1>Date Object Methods Example</h1>

<script>
// Create a new Date object
let currentDate = new Date();

// Display current date and time


document.write("<p>Current Date and Time: " + currentDate + "</p>");

// Get individual components of the date


let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1; // Months are zero-based
let day = currentDate.getDate();
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();

// Display date components


document.write("<p>Year: " + year + "</p>");
document.write("<p>Month: " + month + "</p>");
document.write("<p>Day: " + day + "</p>");
document.write("<p>Time: " + hours + ":" + minutes + ":" + seconds + "</p>");

// Set a specific date and time


let specificDate = new Date(2022, 0, 1, 12, 0, 0);
// January 1, 2022, 12:00 PM
document.write("<p>Specific Date: " + specificDate + "</p>");

// Formatting date
let formattedDate = currentDate.toDateString();
document.write("<p>Formatted Date: " + formattedDate + "</p>");
</script>
</body>
</html>
13.i) Age Calculator using Date object;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Age Calculator</title>
</head>
<body>
<h1>Age Calculator</h1>
<label for="birthdate">Enter your birthdate:</label>
<input type="date" id="birthdate">
<button onclick="calculateAge()">Calculate Age</button>
<p id="result"></p>

<script>
function calculateAge() {
const birthdateString = document.getElementById("birthdate").value;
const birthdate = new Date(birthdateString);
const currentDate = new Date();

const ageInMilliseconds = currentDate - birthdate;


const ageInYears = ageInMilliseconds / (365.25 * 24 * 60 * 60 * 1000);

let res = document.getElementById("result");


res.innerHTML = `Your age is ${ageInYears} years.`;
}
</script>
</body>
</html>

13.ii) Age Calculator using Date object;


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Digital Clock</title>
</head>
<body>
<h1>Digital Clock</h1>
<div id="clock"></div>

<script>
function updateClock() {
const currentTime = new Date();
const hours = currentTime.getHours().toString().padStart(2, '0');
const minutes = currentTime.getMinutes().toString().padStart(2, '0');
const seconds = currentTime.getSeconds().toString().padStart(2, '0');

let res = document.getElementById("clock")


res.innerHTML = `${hours}:${minutes}:${seconds}`;
}

// Update the clock every second


setInterval(updateClock, 1000);

// Initial call to set the initial time


updateClock();
</script>
</body>
</html>
14. Math object:-
JavaScript has a built-in Math object that acts as a collection of mathematical functions and constants. It's
not a module in the sense of being a separate file or module system; it's part of the core JavaScript language.

The Math object provides methods for performing common mathematical operations like rounding,
exponentiation, trigonometry, and more. It also includes mathematical constants like π (pi) and Euler's number (e).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math Object Examples</title>
</head>
<body>
<h1>Math Object Examples</h1>

<h2>Math Constants:</h2>
<p>π (Pi): <span id="pi"></span></p>
<p>e (Euler's Number): <span id="euler"></span></p>

<h2>Basic Mathematical Functions:</h2>


<p>Round: <span id="rounded"></span></p>
<p>Absolute Value: <span id="absolute"></span></p>
<p>Square Root: <span id="squareRoot"></span></p>
<p>Power: <span id="power"></span></p>
<p>Minimum: <span id="minimum"></span></p>
<p>Maximum: <span id="maximum"></span></p>

<h2>Trigonometric Functions:</h2>
<p>Sine: <span id="sine"></span></p>
<p>Cosine: <span id="cosine"></span></p>
<p>Tangent: <span id="tangent"></span></p>

<h2>Random Number Generation:</h2>


<p>Random Floating-Point: <span id="random"></span></p>
<script>
// Math Constants
document.getElementById("pi").innerText = Math.PI;
document.getElementById("euler").innerText = Math.E;

// Basic Mathematical Functions


document.getElementById("rounded").innerText = Math.round(4.7);
document.getElementById("absolute").innerText = Math.abs(-8);
document.getElementById("squareRoot").innerText = Math.sqrt(25);
document.getElementById("power").innerText = Math.pow(2, 3);
document.getElementById("minimum").innerText = Math.min(5, 3, 8);
document.getElementById("maximum").innerText = Math.max(5, 3, 8);

// Trigonometric Functions
document.getElementById("sine").innerText = Math.sin(Math.PI / 2);
document.getElementById("cosine").innerText = Math.cos(Math.PI);
document.getElementById("tangent").innerText = Math.tan(Math.PI / 4);

// Random Number Generation


document.getElementById("random").innerText = Math.random();
</script>
</body>
</html>
15. Browser Object Model (BOM):

The Browser Object Model (BOM) represents the interaction between the browser and the window. It provides
objects and methods for controlling the browser, but it's not standardized, meaning its features may vary between
browsers. Common components of the BOM include the window, screen, document, and navigator objects.

15.i). Window Object Methods with Examples:

a) alert() - Displays an alert dialog with a specified message.

<script>
window.alert("Hello, this is an alert!");
</script>

b) confirm() - Displays a dialog box with a specified message and OK/Cancel buttons.

<script>
let result = window.confirm("Do you want to proceed?");
if (result) {
document.write("User clicked OK.");
} else {
document.write("User clicked Cancel.");
}
</script>

c) prompt() - Displays a dialog box that prompts the user for input.
<script>
let userInput = window.prompt("Enter your name:");
document.write("User entered: " + userInput);
</script>

d) open( ) – opens a new window specified URL

<script>
// Open a new window
window.open("https://www.google.com", "_blank");
</script>

15.ii). Screen Object Methods with Examples:

The screen object represents the properties of the user's screen. Here are a couple of methods:

a) screen.width and screen.height - Retrieve the width and height of the user's screen.

<script>
document.write("Screen Width: " + screen.width);
document.write("Screen Height: " + screen.height);
</script>

b) screen.availWidth and screen.availHeight -Retrieve the available width and height of the user's
screen (excluding taskbars and other system elements).
<script>
document.write("Available Screen Width: " + screen.availWidth);
document.write("Available Screen Height: " + screen.availHeight);
</script>
15.iii).Accessing a geolocation
In JavaScript, you can use the Geolocation API to access the user's geographical location. The
Geolocation API provides a simple way to get the device's location (latitude and longitude).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Geolocation Example</title>
</head>
<body>
<h1>Geolocation</h1>

<button onclick="getLocation()">Get Location</button>

<p id="location"></p>

<script>
let loc = document.getElementById("location");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
loc.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;

loc.innerHTML = "Latitude: " + latitude + "<br>Longitude: " + longitude;


}
</script>
</body>
</html>

You might also like