0% found this document useful (0 votes)
14 views31 pages

Unit Iii

This document provides an overview of JavaScript key concepts and important questions related to client-side processing and scripting. It covers topics such as variables, data types, functions, objects, arrays, and event handling, along with a list of significant questions and coding exercises. The content is aimed at enhancing understanding of JavaScript for web development purposes.

Uploaded by

Deshma
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)
14 views31 pages

Unit Iii

This document provides an overview of JavaScript key concepts and important questions related to client-side processing and scripting. It covers topics such as variables, data types, functions, objects, arrays, and event handling, along with a list of significant questions and coding exercises. The content is aimed at enhancing understanding of JavaScript for web development purposes.

Uploaded by

Deshma
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
You are on page 1/ 31

lOMoARcPSD|32195777

UNI CLIENT SIDE PROCESSING AND SCRIPTING:


JavaScript Key Concepts & Q&A
Web Essentials (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Deshma ([email protected])
lOMoARcPSD|32195777

UNI
T-III
CLIENT SIDE PROCESSING AND SCRIPTING

 Introduction To JavaScript
 Variables And Data types
 Statements
 Operators
 Literals
 Functions
 Objects
 Arrays
 Regular expressions, Event handling
 JavaScript Debuggers

LIST OF IMPORTANT QUESTIONS


1. What is the benefits of using JavaScript code in an HTML
document? Dec-07
2. What is the need for client side scripting?
May-09
3. List out the objects used in JavaScript with its purpose.
May-09,12
4. Comment on the statement . “Each object of a class has its own
instance of static member variable.”
Dec-08
5. What is JavaScript statement? Give an example.
Dec-11
6. Explain array creation in JavaScript with example.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

May-11
7. State the types of JavaScript statements with examples.
Dec-13
8. What are object literal in javascript.
Dec-18
9. Write a JavaScript that searches word in sentence and returns the
index of the word.
Dec-19
10. What are global functions in java Script?
11. Give few operators supported by JavaScript.
May-23
12. List the different built – in objects available in JavaScript.
May-23
13. State the purpose of the following special datatypes associated with
JavaScript.
 BigInt (ES11+)
May-24
 Primitive Wrapper Objects.
14. Write a JavaScript code snippet for Exception handling.
May-24

PART –B
1. Write a Java Script to print “Good Day” using IF-ELSE condition.
May-14
2. List any four methods of date object.
Dec-16
3. How exceptions are handled in JavaScript?
May-17
4. Write a JavaScript that searches a word in sentence and returns the
index of the word.
Dec-19
5. Explain the looping statements supported in JavaScript with
examples. May-23
6. What are exceptions? How exceptions are handled in javascript?
May-23

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

7. Devise a JavaScript program that demonstrate the uses of regular


expressions by creating a simpke HTML page with a textarea (T)
where the end user can input text. When the user clicks the
“Highlight words” button, it should highlight the specific words
(defined in an array) using regular expressions.
May
-24.
8. Explain about the event handling in JavaScript. List down the
various types of events that are supported by Java script. (7)
May-24
9. Describe how event in Javascript move through the DOM tree in two
distinct stages.(6)
May-24
10. Develop a JavaScript page to demonstrate an If condition by which
the time on your browser is less than 10; you will get a “Good
morning” greeting.(8)
D
ec-
08
11. Write a Javascript to find and print the largest and smallest values
among 10 elements of an array. (8)
May-10

ANSWERS:
1. What is the benefits of using JavaScript code in an HTML document?
Dec-07
1. Interactivity
 Dropdown menus
 Image sliders
 Dynamic content updates
2. Dynamic Content Updates
 Live search suggestions
 Real-time notifications
 Chat interfaces

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

3. Improved User Experience:


 Validating form inputs before submission
 Showing/hiding elements
 Animating UI elements
4. Access to Browser and Device Features
 Geolocation
 Camera and microphone access
 Clipboard access
5. Client-Side Processing
 Less load on the server
 Faster response times for users
 Reduced server costs
6. Integration with APIs and Libraries
7. Universal Browser Support
2. What is the need for client side scripting?
May-09
i. Faster User Interaction
ii. Improved User Experience
iii. Reduces Server Load
iv. Dynamic Content Updates
v. Better Responsiveness
vi. Access to Browser Features
3. List out the objects used in JavaScript with its purpose.
May-09,12
In JavaScript, objects are core building blocks that represent real-
world or program-related entities. They group together properties (data)
and methods (functions) into a single structure.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

O The base object from which all other objects inherit.


bject Used to store key-value pairs.
A Used to store multiple values in a single variable (like
rray a list).
S
Used to work with text (strings of characters).
tring
N Handles numeric values and provides useful methods
umber for numbers.
B Represents a logical entity with only two values: true
oolean or false.

4.Comment on the statement . “Each object of a class has its own


instance of static member variable.”
Dec-08
“Each object of a class has its own instance of static member variable.”
The statement is incorrect because static member variables are shared
among all instances of a class.
 A static variable belongs to the class itself, not to individual objects.
 All objects share the same copy of the static variable.
 Changing the value of a static variable through one object will affect it
for all other objects.
5. What is JavaScript statement? Give an example.
Dec-11
JavaScript statement is a command that tells the browser to perform an
action. It can be something like:
 Declaring a variable
 Performing a calculation
 Making a decision
 Looping through data
 Calling a function

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

JavaScript code is made up of many statements, each typically ending with a


semicolon (;), though it's optional in many cases.

6. Explain array creation in JavaScript with example. May-


11
An array is a special variable that can hold multiple values at once, all
stored in a single variable. Arrays are ordered, and items are accessed using
indexes, starting at 0.
Using Array in Javascript:
let fruits = ["apple", "banana", "cherry"];

 This creates an array with 3 string elements.


 fruits[0] is "apple"
 fruits[1] is "banana"
 fruits[2] is "cherry"

7.State the types of JavaScript statements with examples.


Dec-13
1. Variable Declaration Statements
Used to declare variables.

let name = "Alice";


const age = 25;
var city = "Paris";

2. Expression Statements
Performs a calculation or assignment. These are often part of other
statements.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

x = 10 + 5; // Assignment expression
y++; // Increment expression

3. Conditional Statements
Used to make decisions in code.
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

4. Looping (Iteration) Statements


Used to repeat blocks of code.
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}

// While loop
let i = 0;
while (i < 3) {
console.log("Hello");
i++;

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

5. Function Declaration Statements


Used to define reusable blocks of code (functions).
function greet(name) {
console.log("Hello, " + name);
}
greet("Alice");

6. Switch Statement
Used to handle multiple conditions.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("Weekend is near!");
break;
default:
console.log("Midweek day");}

7. Try…Catch Statement (Exception Handling)


Used to handle errors in code gracefully.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

try {
let result = riskyFunction();
} catch (error) {
console.log("Something went wrong:", error);}
8. Return Statement
Used to return a value from a function.
function add(a, b)
{
return a + b;
}

9. Break and Continue Statements


Used to control loop execution.
for (let i = 0; i < 10; i++) {
if (i === 5) break; // Exits the loop
if (i === 3) continue; // Skips this
iteration
console.log(i);
}

8.What are object literal in javascript.


Dec-18
An object literal in JavaScript is a simple and direct way to create an
object using a pair of curly braces {}, containing key-value pairs.

let person = {

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

name: "Alice",
age: 25,
city: "New York",
greet: function() {
console.log("Hello, " + this.name);
}
};

9.Write a JavaScript that searches word in sentence and returns the


index of the word.
Dec-19
function findWordIndex(sentence, word) {
let index = sentence.indexOf(word);
if (index !== -1) {
console.log(`The word "${word}" is found at index ${index}.`);
} else {
console.log(`The word "${word}" was not found in the
sentence.`);
} return index;}
// Example usage
let sentence = "JavaScript is a powerful scripting language.";
let wordToFind = "powerful";

findWordIndex(sentence, wordToFind);

10.What are global functions in java Script?

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Global functions in JavaScript are built-in functions that are available


anywhere in your code. you don’t need to create them or import anything.
They are part of the global scope, which means you can call them directly
from anywhere in your script.
Function Purpose
alert() Displays a popup alert box in the browser.
prompt() Displays a dialog box that prompts the user for input.
confirm() Displays a dialog box with OK and Cancel buttons.
parseInt() Converts a string to an integer.
parseFloa
Converts a string to a floating-point number.
t()
isNaN() Checks if a value is "Not-a-Number".
isFinite() Checks if a value is a finite number.
encodeU
Encodes a URI by escaping special characters.
RI()
decodeU
Decodes an encoded URI.
RI()
eval() Executes a string as JavaScript code

11.Give few operators supported by JavaScript. May-


23
1. Arithmetic Operators:
 + (Addition): 5 + 2 → 7
 - (Subtraction): 5 - 2 → 3
 * (Multiplication): 5 * 2 → 10
 / (Division): 5 / 2 → 2.5
 % (Modulus): 5 % 2 → 1
 ** (Exponentiation): 5 ** 2 → 25

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

2. Assignment Operators
 = (Assignment): x = 10
 += (Add and assign): x += 5 → same as x = x + 5
 -= (Subtract and assign)
 *= (Multiply and assign)
 /= (Divide and assign)
3. Comparison Operators
 == (Equal to): 5 == '5' → true (type coercion)
 === (Strict equal): 5 === '5' → false
 != (Not equal)
 !== (Strict not equal)
 > (Greater than)
 < (Less than)
 >= (Greater than or equal to)
 <= (Less than or equal to)
4. Logical Operators
 && (Logical AND)
 || (Logical OR)
 ! (Logical NOT)
5. Bitwise Operators
 &, |, ^, ~, <<, >>, >>>
6. Unary Operators
 typeof (Returns the type of a variable)
 delete (Deletes an object property)
 ++ (Increment)
 -- (Decrement)

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

7. Ternary Operator
 condition?expr1:expr2
Example: let result = (a > b) ? "A" : "B";
12.List the different built – in objects available in JavaScript.
May-23
1. Fundamental Objects
 Object
 Function
 Boolean
 Symbol
 BigInt
2. Numbers and Dates
 Number
 Math
 Date
3. Text Processing
 String
 RegExp
4. Indexed Collections
 Array
 Int8Array, Uint8Array, Uint8ClampedArray
 Int16Array, Uint16Array
 Int32Array, Uint32Array
 Float32Array, Float64Array
5. Keyed Collections
 Map

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

 Set
 WeakMap
 WeakSet
6. Structured Data
 ArrayBuffer
 SharedArrayBuffer
 DataView
 JSON
7. Control Abstractions
 Promise
 Generator
 GeneratorFunction
 AsyncFunction
8. Reflection and Introspection
 Reflect
 Proxy
9. Error Objects
 Error
 SyntaxError
 ReferenceError
 TypeError
 RangeError
 URIError
 EvalError

13.State the purpose of the following special datatypes associated with

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

JavaScript.
JavaScript has a few special (or primitive) datatypes like:
1. undefined
2. null
3. Symbol
4. BigInt
5. NaN (technically a special value of the Number type)

14.Define BigInt (ES11+)


May-24
BigInt is a built-in JavaScript data type introduced in ES11
(ECMAScript 2020) that allows you to work with integers of arbitrary length,
beyond the safe limits of the Number type.
1. Using the n suffix:
let big1 = 9007199254740991n;

2. Using the BigInt() function:


let big2 =
BigInt("900719925474099123456789");

15.List Primitive Wrapper Objects.


In JavaScript, Primitive Wrapper Objects are special objects that wrap
around primitive data types to provide them with object-like capabilities
(like methods and properties).
Primitive
Wrapper Object
Type
String String
Number Number

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Boolea
Boolean
n
Sym
Symbol
bol
BigI
BigInt
nt

16.Write a JavaScript code snippet for Exception handling. May-


24

try {
// Code that may throw an error
let result = riskyOperation();
console.log("Result:", result);
} catch (error) {
// Code to handle the error
console.error("An error occurred:", error.message);
} finally {
// This block always runs (optional)
console.log("Execution completed.");
}

// Function for demo


function riskyOperation() {
// Intentionally throw an error
throw new Error("Something went wrong!");
}

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

ANSWERS PART –B
1. Write a Java Script to print “Good Day” using IF-ELSE condition.
May-14
<html>
<head>
<script>
Function MyMessage()
{
Var today=new Date();
Var h=today.getHours();
If(h<12)//After 12 O’clock Say Good Bye
//Before 12 O’clock say Good Day
Document.wite(“Good Bye”);
}
</script>
</head>
<body on;oad=”MyMessage()”>
</body>
</html>

2. List any four methods of date object.


Dec-16

Method Meaning
getTime() It returns the number of milliseconds. This
value is the difference between the current time
and the time value from 1st January 1970.
getDate() Returns the current date based on computers
local time.
getDay() Returns the current day. The day number is
from 0 to 6 i.e. from Sunday to Saturday.
getHours() Returns the hour value ranging from 0 to 23,
based on loacal time.
getSeconds() Returns the second value ranging from 0 to 59,
based on local time.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

3. How exceptions are handled in JavaScript?


May-17
The expections are handled in Javascript using try… catch blocks.
<html>
<head>
<script type=”text/javascript>
<!—
function myFunc()
{
var a=100;
var b=0;
try{
if(b= = 0){
throw(“Divide by zero error.”);
}
else
{
var c =a/b;
}
}
catch(e) {
alert(“Error:” +e);
}
}
//-->
</script>
</head>

4. Write a JavaScript that searches a word in sentence and returns


the index of the word.
Dec-19

<!DOCTYPE html>
<head>
<script type=”text/javascript>

// Ask user for a sentence and a word to search


let sentence = prompt("Enter a sentence:");
let wordToSearch = prompt("Enter the word to search:");

// Search for the word in the sentence

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

let index = sentence.indexOf(wordToSearch);

// Display the result


if (index !== -1) {
alert(`The word "${wordToSearch}" was found at index $
{index}.`);
} else {
alert(`The word "${wordToSearch}" was not found in the
sentence.`);
}
</script>
</head>

5. Explain the looping statements supported in JavaScript with examples.


May-
23

JavaScript supports several looping statements that allow code to be


executed repeatedly based on a condition. Here are the main ones, with examples:

1. for loop

Used when the number of iterations is known.


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

Output:

javascript
CopyEdit
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

2. while loop

Used when the number of iterations is unknown and based on a condition.


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

3. do...while loop

Same as while, but it runs at least once even if the condition is false.

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

4. for...in loop

Used to loop through the properties of an object.


let person = { name: "Alice", age: 25, city: "New York" };
for (let key in person) {
console.log(key + ": " + person[key]);
}

5. for...of loop

Used to loop through iterable objects like arrays, strings, etc.


let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}

6.break and continue

 break: exits the loop early.


 continue: skips the current iteration.

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

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

if (i === 3) break;
console.log(i); // prints 0, 1, 2
}

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


if (i === 2) continue;
console.log(i); // prints 0, 1, 3, 4
}

6. What are exceptions? How exceptions are handled in javascript? May-


23
An exception is an error that occurs during the execution of a program.
When something goes wrong (like trying to access an undefined variable or
divide by zero), JavaScript throws an exception to indicate that an error has
occurred.

let result = 10 / 0;
console.log(result); // Infinity (not an exception)

let x = undefinedVariable; // ReferenceError: undefinedVariable is


not defined

How Are Exceptions Handled in JavaScript?

JavaScript handles exceptions using try...catch statements. This lets you


write code that might throw an error, and then handle that error gracefully
without crashing your program.

Syntax:
try {

// Code that may throw an exception

} catch (error) {

// Code to handle the error

} finally {

// (Optional) Code that will always run, error or not

Example:

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

try {

let result = riskyFunction(); // might throw an error

console.log(result);

} catch (error) {

console.log("An error occurred: " + error.message);

} finally {

console.log("This block always runs.");

7. Devise a JavaScript program that demonstrate the uses of regular


expressions by creating a simple HTML page with a text area (T) where the
end user can input text. When the user clicks the “Highlight words” button,
it should highlight the specific words (defined in an array) using regular
expressions.
May-
24.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Highlight Words with Regex</title>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
#output {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
white-space: pre-wrap;
}
</style>
</head>
<body>

<h2>Highlight Words</h2>
<textarea id="textInput" rows="8" cols="50"
placeholder="Type or paste your text

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

here..."></textarea><br><br>
<button onclick="highlightWords()">Highlight
words</button>

<div id="output"></div>

<script>
function highlightWords() {
const inputText =
document.getElementById("textInput").value;
const outputDiv =
document.getElementById("output");

// Define the words to highlight


const wordsToHighlight = ["JavaScript",
"HTML", "CSS", "regex", "highlight"];

// Create a regex pattern that matches all


the words (case-insensitive)
Const regex = new RegExp("\\b("+
wordsToHighlight.join("|") + ")\\b", "gi");

// Replace the matched words with highlighted


span
const highlighted Text =
inputText.replace(regex, (match) => {
return `<span
class="highlight">${match}</span>`;
});

// Display the result


outputDiv.innerHTML = highlightedText;
}
</script>

</body>
</html>

8. Explain about the event handling in JavaScript. List down the various types
of events that are supported by Java script. (7)
May-24
Event handling in JavaScript is a way to execute code in response to
interactions or occurrences (called events) on a web page. Events can be user
actions like clicking, typing, hovering, or system-generated actions like page
loading, media playing, etc.
You use event listeners (also called event handlers) to respond to these events.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

How Event Handling Works

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

Ways to Handle Events


1. Inline HTML event attribute

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

2. DOM property method

button.onclick = function() {
alert("Hello!");
};

3. addEventListener (preferred and flexible)

button.addEventListener("click", sayHello);

📋 Common JavaScript Events


Here are some popular event types categorized by usage:
🖱️ Mouse Events
Event Description
click Fired when an element is clicked
dblclick Fired on a double-click
mouseover When pointer enters an element
mouseout When pointer leaves an element
mousedown Mouse button is pressed down
mouseup Mouse button is released
mousemove Pointer is moved

⌨️ Keyboard Events
Event Description
keydown A key is pressed down
keyup A key is released
keypress A key is pressed (deprecated, use keydown)

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

📝 Form Events
Event Description
submit Form is submitted
change Value of input, select, or textarea changes
input Value of an <input> or <textarea> is modified
focus Element gains focus
blur Element loses focus

🌐 Window Events
Event Description
load Page finishes loading
resize Window is resized
scroll User scrolls the page
unload Page is unloaded

📦 Miscellaneous Events
Event Description
Contextmenu Right-click on an element
Touchstart Touch starts on a touchscreen
Touchend Touch ends
Dragstart Dragging starts
Drop Item is dropped

12.Describe how event in Javascript move through the DOM tree in two
distinct stages. (6) May-
24
In JavaScript, events move through the DOM tree in a process called
event propagation, which happens in two main stages (actually three, but
usually two are emphasized). Here's how it works:

Event Propagation Stages in the DOM

1. Capturing Phase (a.k.a. Capture Phase or Trickling Down)


 The event starts at the root of the DOM tree (usually the window or document) and
travels down to the target element.
 This is the first phase, where parent elements get a chance to intercept the event
before it reaches the target.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

element.addEventListener('click', handler, true); // true


enables capture phase

2. Target Phase
 The event reaches the target element — the exact element that was interacted with.
 Both capturing and bubbling listeners can run on the target element during this
phase.

3. Bubbling Phase (a.k.a. Bubble Up)


 After reaching the target, the event bubbles back up the DOM tree from the target to
the root.
 This is the most commonly used phase because the default for addEventListener is
bubbling.

element.addEventListener('click', handler); // false (or


omitted) defaults to bubbling

🖼️ Visual Flow:

Document
└── <div id="outer">
└── <button id="inner">Click me</button>
If you click the <button>:
1. Capture Phase: document → div#outer → button#inner
2. Target Phase: Event runs on button#inner
3. Bubble Phase: button#inner → div#outer → document

Example Code:

<div id="outer">
<button id="inner">Click Me</button>
</div>

<script>
document.getElementById("outer").addEventListener("click",
() => {
console.log("Outer DIV (bubbling)");
});

document.getElementById("outer").addEventListener("click",
() => {
console.log("Outer DIV (capturing)");
}, true);

document.getElementById("inner").addEventListener("click",

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

() => {
console.log("Button (target)");
});
</script>

When you click the button, you’ll see this output:

Outer DIV (capturing)


Button (target)
Outer DIV (bubbling)

13.Develop a JavaScript page to demonstrate an If condition by which the


time on your browser is less than 10; you will get a “Good morning”
greeting.(8)

JavaScript If Condition Example (Time Check)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Good Morning Greeting</title>
</head>
<body>

<h2>Greeting Based on Time</h2>


<p id="greeting"></p>

<script>
// Get the current hour from browser
const currentHour = new Date().getHours();

// Check if the time is before 10 AM


if (currentHour < 10) {
document.getElementById("greeting").textContent =
"Good morning!";
} else {
document.getElementById("greeting").textContent =
"Have a great day!";
}
</script>

</body>
</html>

14. Write a Javascript to find and print the largest and smallest values
among 10 elements of an array.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

JavaScript: Find Largest and Smallest in an Array

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Largest and Smallest Finder</title>
</head>
<body>

<h2>Find Largest and Smallest Values</h2>


<p id="result"></p>

<script>
// Define an array of 10 numbers
const numbers = [12, 5, 89, 34, 7, 22, 67, 3, 99, 15];

// Find smallest and largest using Math


const smallest = Math.min(...numbers);
const largest = Math.max(...numbers);

// Display the result


document.getElementById("result").innerHTML =
"Array: [" + numbers.join(", ") + "]<br>" +
"Smallest value: " + smallest + "<br>" +
"Largest value: " + largest;
</script>

</body>
</html>

 Math.min(...numbers) finds the smallest number.


 Math.max(...numbers) finds the largest number.
 The spread operator (...) expands the array into individual arguments.

14. Develop a JavaScript page to demonstrate an If condition by which the time


on your browser is less than 10; you will get a “Good morning” greeting.(8)
Dec-08

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Greeting Based on Time</title>

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

</head>
<body>

<h2>Time-Based Greeting</h2>
<p id="message"></p>

<script>
// Get the current hour using JavaScript's Date object
const currentHour = new Date().getHours();

// Display "Good morning" if the time is before 10 AM


if (currentHour < 10) {
document.getElementById("message").textContent = "Good
morning!";
}
</script>

</body>
</html>

15.Write a Javascript to find and print the largest and smallest values among 10
elements of an array. (8) May-10

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Find Largest and Smallest</title>
</head>
<body>

<h2>Largest and Smallest Value in an Array</h2>


<p id="output"></p>

<script>
// Define an array with 10 numbers
const numbers = [23, 5, 88, 42, 16, 77, 9, 34, 1, 60];

// Initialize smallest and largest to the first element


let smallest = numbers[0];
let largest = numbers[0];

// Loop through the array to find the smallest and largest


for (let i = 1; i < numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
}
if (numbers[i] > largest) {
largest = numbers[i];

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

}
}

// Display the results


document.getElementById("output").innerHTML =
"Array: [" + numbers.join(", ") + "]<br>" +
"Smallest Value: " + smallest + "<br>" +
"Largest Value: " + largest;
</script>

</body>
</html>

Downloaded by Deshma ([email protected])

You might also like