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

Javascript

Uploaded by

ashutoshwagh767
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)
21 views43 pages

Javascript

Uploaded by

ashutoshwagh767
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/ 43

Assignment: JavaScript (7T203) - Unit I & Unit II Assignment: JavaScript

(7T203) - Unit I & Unit II UNIT I – Basics of JavaScript Programming

1. Write a JavaScript program to print even numbers from 1 to 10 using a


loop.
<!DOCTYPE html>

<html>

<head>

<title>Even Numbers from 1 to 10</title>

</head>

<body>

<h1>Even Numbers from 1 to 10</h1>

<ul id="even-numbers"></ul>

<script>

// Get reference to the HTML element where we'll show the numbers

const list = document.getElementById('even-numbers');

// Loop from 1 to 10

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

if (i % 2 === 0) {

console.log(i); // Also log to browser console

// Create a new list item and add it to the list

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

listItem.textContent = i;

list.appendChild(listItem);

}
}

</script>

</body>

</html>

2. Differentiate between `if`, `if...else`, and `switch` statements with syntax.

1. if Statement

Use when: You want to run code based on a single condition.

Syntax:

if (condition) {

// code to run if condition is true

Example:

let age = 18;

if (age >= 18) {

console.log("You are eligible to vote.");

2. if...else Statement

Use when: You want to run one block of code if a condition is true, and another if it is false.

Syntax:

if (condition) {

// code if condition is true

} else {

// code if condition is false

Example:
let age = 16;

if (age >= 18) {

console.log("You are eligible to vote.");

} else {

console.log("You are not eligible to vote.");

3. switch Statement

Use when: You need to compare one value against multiple possible values (especially for
discrete choices).

Syntax:

switch(expression) {

case value1:

// code to run if expression === value1

break;

case value2:

// code to run if expression === value2

break;

default:

// code to run if none of the above cases match

Example:

let day = 3;

switch(day) {

case 1:

console.log("Monday");

break;

case 2:
console.log("Tuesday");

break;

case 3:

console.log("Wednesday");

break;

default:

console.log("Another day");

3.What are the key features of JavaScript? Explain with examples.


Key Features of JavaScript

Here are some key features of JavaScript that make it a powerful language for web development:

• Client-Side Scripting:JavaScript runs on the user's browser, so has a faster response time
without needing to communicate with the server.

• Versatile: JavaScript can be used for a wide range of tasks, from simple calculations to
complex server-side applications.

• Event-Driven: JavaScript can respond to user actions (clicks, keystrokes) in real-time.

• Asynchronous: JavaScript can handle tasks like fetching data from servers without freezing
the user interface.

• Rich Ecosystem: There are numerous libraries and frameworks built on JavaScript, such
as React, Angular, and Vue.js, which make development faster and more efficient.

Client Side and Server Side nature of JavaScript

client side and server side

JavaScript's flexibility extends to both the client-side and server-side, allowing developers to
create complete web applications. Here’s how it functions in each environment:

Client-Side:

• Involves controlling the browser and its DOM (Document Object Model).

• Handles user events like clicks and form inputs.

• Common libraries include AngularJS, ReactJS, and VueJS.

Server-Side:

• Involves interacting with databases, manipulating files, and generating responses.


• Node.js and frameworks like Express.js are widely used for server-side JavaScript, enabling
full-stack development.

3. Create a JavaScript object `car` with properties and methods, update a property,
and delete a property
// 1. Create a JavaScript object named 'car'
let car = {
brand: "Toyota",
model: "Corolla",
year: 2020,
color: "Red",

// Method
start: function() {
console.log("The car has started.");
},

displayInfo: function() {
console.log(`Car: ${this.brand} ${this.model}, Year: ${this.year}, Color:
${this.color}`);
}
};

// Use the object


car.start(); // Method call
car.displayInfo(); // Show initial info

// 2. Update a property
car.color = "Blue"; // Change color from Red to Blue
console.log("Updated color:", car.color);

// 3. Delete a property
delete car.year;
console.log("After deleting 'year' property:");
console.log(car);

// Optional: Try to display info again


car.displayInfo(); // Now year is missing

//output
The car has started.
Car: Toyota Corolla, Year: 2020, Color: Red
Updated color: Blue
After deleting 'year' property:
{ brand: 'Toyota', model: 'Corolla', color: 'Blue', start: [Function], displayInfo:
[Function] }
Car: Toyota Corolla, Year: undefined, Color: Blue

4. Write JavaScript code using `if...else if...else` statements to find the


largest of three numbers.
<!DOCTYPE html>

<html>

<head>

<title>Find the Largest Number</title>

</head>

<body>

<h1>Find the Largest of Three Numbers</h1>

<label for="num1">Enter first number:</label>

<input type="number" id="num1"><br><br>

<label for="num2">Enter second number:</label>

<input type="number" id="num2"><br><br>

<label for="num3">Enter third number:</label>

<input type="number" id="num3"><br><br>

<button onclick="findLargest()">Find Largest</button>

<h2 id="result"></h2>
<script>

function findLargest() {

// Get input values and convert to numbers

let num1 = parseFloat(document.getElementById('num1').value);

let num2 = parseFloat(document.getElementById('num2').value);

let num3 = parseFloat(document.getElementById('num3').value);

let largest;

// Check if the inputs are valid numbers

if (isNaN(num1) || isNaN(num2) || isNaN(num3)) {

document.getElementById('result').textContent = "Please enter all three numbers.";

return;

// Use if...else if...else to find the largest number

if (num1 >= num2 && num1 >= num3) {

largest = num1;

} else if (num2 >= num1 && num2 >= num3) {

largest = num2;

} else {

largest = num3;

// Display the result

document.getElementById('result').textContent = "The largest number is: " + largest;

console.log("The largest number is:", largest);

</script>
</body>

</html>

5. Develop a JavaScript program using `if...else` to check whether a given number is


Even or Odd.
<!DOCTYPE html>
<html>
<head>
<title>Even or Odd Checker</title>
</head>
<body>

<h1>Check if a Number is Even or Odd</h1>

<label for="number">Enter a number:</label>


<input type="number" id="number">
<button onclick="checkEvenOdd()">Check</button>

<h2 id="result"></h2>

<script>
function checkEvenOdd() {
// Get input value and convert it to a number
let num = parseInt(document.getElementById("number").value);

// Check for valid input


if (isNaN(num)) {
document.getElementById("result").textContent = "Please enter a valid
number.";
return;
}

// Use if...else to check even or odd


if (num % 2 === 0) {
document.getElementById("result").textContent = num + " is an Even number.";
console.log(num + " is Even.");
} else {
document.getElementById("result").textContent = num + " is an Odd number.";
console.log(num + " is Odd.");
}
}
</script>

</body>
</html>

6. Explain the syntax of `switch` statement with an example.

Switch Statement in JavaScript (4 Marks)


Theory:

The switch statement in JavaScript is used to perform different actions based on


different values of a single expression. It compares the value of an expression with
multiple case values, and executes the block where a match is found.

It is often used as a cleaner alternative to multiple if...else if statements, especially


when checking the same variable for multiple specific values.

<!DOCTYPE html>

<html>

<head>

<title>Day of the Week Checker</title>

</head>

<body>

<h1>Enter a Number (1 to 7) to Get the Day</h1>

<label for="dayInput">Enter a number (1-7):</label>

<input type="number" id="dayInput" min="1" max="7">

<button onclick="checkDay()">Check Day</button>

<h2 id="result"></h2>
<script>

function checkDay() {

let day = parseInt(document.getElementById("dayInput").value);

let dayName;

switch (day) {

case 1:

dayName = "Monday";

break;

case 2:

dayName = "Tuesday";

break;

case 3:

dayName = "Wednesday";

break;

case 4:

dayName = "Thursday";

break;

case 5:

dayName = "Friday";

break;

case 6:

dayName = "Saturday";

break;

case 7:
dayName = "Sunday";

break;

default:

dayName = "Invalid input! Please enter a number between 1 and 7.";

document.getElementById("result").textContent = "Day: " + dayName;

console.log("Day: " + dayName);

</script>

</body>

</html>

7. Create a JavaScript code that uses nested `if...else` statements to find the largest
of three numbers

<!DOCTYPE html>

<html>

<head>

<title>Largest of Three Numbers</title>

</head>

<body>

<h1>Find the Largest of Three Numbers</h1>

<label for="num1">First number:</label>

<input type="number" id="num1"><br><br>


<label for="num2">Second number:</label>

<input type="number" id="num2"><br><br>

<label for="num3">Third number:</label>

<input type="number" id="num3"><br><br>

<button onclick="findLargest()">Find Largest</button>

<h2 id="result"></h2>

<script>

function findLargest() {

let num1 = parseFloat(document.getElementById('num1').value);

let num2 = parseFloat(document.getElementById('num2').value);

let num3 = parseFloat(document.getElementById('num3').value);

if (isNaN(num1) || isNaN(num2) || isNaN(num3)) {

document.getElementById('result').textContent = "Please enter valid numbers in all


fields.";

return;

let largest;

if (num1 >= num2) {


if (num1 >= num3) {

largest = num1;

} else {

largest = num3;

} else {

if (num2 >= num3) {

largest = num2;

} else {

largest = num3;

document.getElementById('result').textContent = "The largest number is: " + largest;

console.log("Largest number:", largest);

</script>

</body>

</html>

9. Demonstrate how to declare and access object properties using dot notation.

Declaring and Accessing Object Properties Using Dot Notation (4 Marks)

Theory:

In JavaScript, objects are collections of key-value pairs called properties. You can declare an
object by listing its properties inside curly braces {}. To access or retrieve the value of a
property, you use dot notation, which consists of the object name followed by a dot (.) and
the property name.

Dot notation is simple and readable, commonly used when the property name is a valid
identifier (no spaces or special characters).

Example:

// Declare an object

let car = {

brand: "Honda",

model: "Civic",

year: 2022

};

// Access properties using dot notation

console.log(car.brand); // Output: Honda

console.log(car.model); // Output: Civic

console.log(car.year); // Output: 2022

10. Develop a program to demonstrate the use of `for...in` loop to iterate through object
properties.

Using for...in Loop to Iterate Object Properties (4 Marks)

Theory:

The for...in loop in JavaScript is used to iterate over the enumerable properties (keys) of an
object. During each iteration, the loop variable holds the name of a property (key), which can
then be used to access the corresponding value. This loop is useful to examine or manipulate
all properties of an object without knowing their names in advance.

Example:

// Declare an object
let book = {

title: "The Alchemist",

author: "Paulo Coelho",

year: 1988

};

// Iterate over object properties using for...in loop

for (let key in book) {

console.log(key + ": " + book[key]);

6 Marks Questions:

1. Write a JavaScript program to input a number and check


whether it is prime using loops.

Checking Prime Number Using Loops in JavaScript (6 Marks)

Theory:

A prime number is a natural number greater than 1 that has no positive


divisors other than 1 and itself. In other words, a prime number can
only be divided evenly (without a remainder) by 1 and the number
itself.

To check if a number n is prime:

1. If n is less than 2, it is not prime.


2. Loop from 2 to √n (square root of n) — since if n has any divisor larger
than its square root, it must have a corresponding divisor smaller than the
square root.
3. For each number i in this range, check if n % i === 0 (i.e., if n is divisible
by i).
4. If any divisor is found, n is not prime.
5. If no divisors are found, n is prime.
Using loops in this way optimizes the process and avoids unnecessary
checks.

Example Program (HTML + JavaScript):

<!DOCTYPE html>

<html>

<head>

<title>Prime Number Checker</title>

</head>

<body>

<h1>Check if a Number is Prime</h1>

<label for="numberInput">Enter a number:</label>

<input type="number" id="numberInput" min="1">

<button onclick="checkPrime()">Check</button>

<h2 id="result"></h2>

<script>

function checkPrime() {

let num =
parseInt(document.getElementById('numberInput').value);

let result = document.getElementById('result');


// Validate input

if (isNaN(num) || num < 1) {

result.textContent = "Please enter a valid positive integer.";

return;

if (num === 1) {

result.textContent = "1 is neither prime nor composite.";

return;

let isPrime = true;

// Check divisors from 2 to square root of num

for (let i = 2; i <= Math.sqrt(num); i++) {

if (num % i === 0) {

isPrime = false;

break; // No need to check further if divisor found

// Display result
if (isPrime) {

result.textContent = num + " is a prime number.";

} else {

result.textContent = num + " is not a prime number.";

</script>

</body>

</html>

2. Write a JavaScript program using `for`, `while`, and


`do...while` to calculate factorial of a number.
• Calculating Factorial Using Different Loops (for,
while, do...while)
• Theory:
• The factorial of a non-negative integer n (denoted as n!) is the product of all positive
integers less than or equal to n. For example:
• 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 =
1205!=5×4×3×2×1=120
• Factorials are commonly used in permutations, combinations, and mathematical
computations.

• 1. Factorial Using for Loop
• function factorialFor(n) {
• let result = 1;
• for (let i = 1; i <= n; i++) {
• result *= i;
• }
• return result;
• }

• console.log("Factorial using for loop:", factorialFor(5)); //
Output: 120

• 2. Factorial Using while Loop
• function factorialWhile(n) {
• let result = 1;
• let i = 1;
• while (i <= n) {
• result *= i;
• i++;
• }
• return result;
• }

• console.log("Factorial using while loop:", factorialWhile(5)); //
Output: 120

• 3. Factorial Using do...while Loop
• function factorialDoWhile(n) {
• let result = 1;
• let i = 1;
• if (n === 0) return 1; // Special case: 0! = 1

• do {
• result *= i;
• i++;
• } while (i <= n);

• return result;
• }

• console.log("Factorial using do...while loop:", factorialDoWhile(5));

2.Develop a JavaScript program to take a number (N) and print its


multiplication table from 1 to 10.

<!DOCTYPE html>

<html>

<head>

<title>Multiplication Table</title>

</head>

<body>

<h1>Print Multiplication Table</h1>


<label for="numberInput">Enter a number:</label>

<input type="number" id="numberInput">

<button onclick="printTable()">Print Table</button>

<pre id="result"></pre>

<script>

function printTable() {

let num = parseInt(document.getElementById('numberInput').value);

let output = '';

if (isNaN(num)) {

document.getElementById('result').textContent = "Please enter a valid


number.";

return;

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

output += `${num} x ${i} = ${num * i}\n`;

document.getElementById('result').textContent = output;

console.log(output);

}
</script>

</body>

</html>

4. Explain arithmetic, relational, and logical operators in JavaScript with


examples.

JavaScript Operators Explained (4 Marks)

1. Arithmetic Operators

These operators perform mathematical calculations on numeric values.

Operator Description Example Result


+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 10 / 2 5
% Modulus (remainder) 10 % 3 1
++ Increment let x = 5; x++ 6
-- Decrement let x = 5; x-- 4

Example:

let a = 10;

let b = 3;

console.log(a + b); // 13

console.log(a % b); // 1

2. Relational Operators

These operators compare two values and return a Boolean (true or false).
Operator Description Example Result
== Equal to 5 == '5' true
=== Strict equal to (type & value) 5 === '5' false
!= Not equal to 5 != 3 true
!== Strict not equal to 5 !== '5' true
> Greater than 5>3 true
< Less than 3<5 true
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 3 <= 5 true

Example:

let x = 7;

console.log(x > 5); // true

console.log(x === 7); // true

console.log(x != 7); // false

3. Logical Operators

These operators combine multiple Boolean expressions and return a Boolean


result.

Operator Description Example Result


&& Logical AND (true && false) false
` ` Logical OR
! Logical NOT (negation) !true false

Example:

let a = 5, b = 10;

console.log(a > 0 && b > 5); // true (both true)

console.log(a > 10 || b > 5); // true (second true)


console.log(!(a > 0)); // false (negation of

6. Explain different types of expressions in JavaScript with suitable


examples.

Different Types of Expressions in JavaScript (4 Marks)


7. 1. Arithmetic Expressions
8. These expressions perform mathematical calculations and return numeric results.
9. Example:
10. let sum = 5 + 3 * 2; // Evaluates to 5 + 6 = 11
11.
12. 2. String Expressions
13. Expressions that involve string concatenation or manipulation.
14. Example:
15. let greeting = "Hello, " + "world!"; // "Hello, world!"
16.
17. 3. Relational Expressions
18. These expressions compare two values and return a Boolean (true or false).
19. Example:
20. let isEqual = (10 === 10); // true
21. let isGreater = (5 > 3); // true
22.
23. 4. Logical Expressions
24. Expressions that combine Boolean values using logical operators and return a
Boolean result.
25. Example:
26. let canVote = (age >= 18 && citizenship === "USA");
27.
28. 5. Assignment Expressions
29. Expressions that assign a value to a variable.
30. Example:
31. let x = 10; // Assigns 10 to x

6. Create a JavaScript object `car` with getter and setter methods and
demonstrate their use.
JavaScript Object with Getter and Setter Methods
Theory:
• Getter methods allow you to access the value of a property
indirectly.
• Setter methods let you modify or validate the value before setting
it.
• Using getters and setters encapsulates the internal data, allowing
control over how properties are accessed or modified.

Example:
let car = {
_brand: "Toyota", // Note: underscore prefix denotes a "private"
property convention
_year: 2018,
// Getter for brand
get brand() {
return this._brand;
},

// Setter for brand


set brand(newBrand) {
if (typeof newBrand === "string" && newBrand.length > 0) {
this._brand = newBrand;
} else {
console.log("Invalid brand name");
}
},

// Getter for year


get year() {
return this._year;
},

// Setter for year with validation


set year(newYear) {
if (typeof newYear === "number" && newYear > 1900 && newYear <= new
Date().getFullYear()) {
this._year = newYear;
} else {
console.log("Invalid year");
}
}
};

// Using the getter


console.log("Brand:", car.brand); // Output: Toyota
console.log("Year:", car.year); // Output: 2018

// Using the setter


car.brand = "Honda";
car.year = 2022;

console.log("Updated Brand:", car.brand); // Output: Honda


console.log("Updated Year:", car.year); // Output: 2022

// Trying to set invalid values


car.brand = ""; // Output: Invalid brand name
car.year = 1800; // Output: Invalid year

Explanation:
• Properties _brand and _year are considered “private” by convention.
• Getters brand and year provide access to these properties.
• Setters brand and year validate inputs before updating the
properties.
• This approach ensures data integrity and controlled access.

8. Write a complete JavaScript code to calculate the sum of the first 10


natural numbers using a loop.
// Initialize sum variable
let sum = 0;

// Loop from 1 to 10 and add each number to sum


for (let i = 1; i <= 10; i++) {
sum += i;
}

// Display the result


console.log("Sum of the first 10 natural numbers is:", sum);

9. Develop a JavaScript program to input a number (N) and calculate


factorial using loops.
<!DOCTYPE html>
<html>
<head>
<title>Factorial Calculator</title>
</head>
<body>

<h1>Calculate Factorial</h1>

<label for="numberInput">Enter a non-negative integer:</label>


<input type="number" id="numberInput" min="0" />
<button onclick="calculateFactorial()">Calculate</button>

<h2 id="result"></h2>

<script>
function calculateFactorial() {
let input = document.getElementById('numberInput').value;
let N = parseInt(input);
let resultElement = document.getElementById('result');

if (isNaN(N) || N < 0) {
resultElement.textContent = "Please enter a valid non-negative
integer.";
return;
}

let factorial = 1;

for (let i = 1; i <= N; i++) {


factorial *= i;
}

resultElement.textContent = `Factorial of ${N} is: ${factorial}`;


}
</script>
</body>
</html>
UNIT II – Array, Function and String
4 Marks Questions:

1. Write JavaScript code to find the **maximum value** in an


array using `for` loop.
let numbers = [5, 12, 8, 20, 3, 15];

let max = numbers[0]; // Assume first element is max initially

for (let i = 1; i < numbers.length; i++) {


if (numbers[i] > max) {
max = numbers[i];
}
}

console.log("Maximum value in the array is:", max);

2. Write JavaScript code to find the **minimum value** in an


array using `for` loop.
let numbers = [5, 12, 8, 20, 3, 15];

let min = numbers[0]; // Assume first element is min initially

for (let i = 1; i < numbers.length; i++) {


if (numbers[i] < min) {
min = numbers[i];
}
}

console.log("Minimum value in the array is:", min);

3. Write a JavaScript function `isPalindrome(str)` to check


whether a string is a palindrome.
function isPalindrome(str) {
// Convert string to lowercase and remove non-alphanumeric
characters for accurate checking
let cleanedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');

// Reverse the cleaned string


let reversedStr = cleanedStr.split('').reverse().join('');
// Check if original cleaned string equals reversed string
return cleanedStr === reversedStr;
}

// Example usage:
console.log(isPalindrome("Madam")); // true
console.log(isPalindrome("Hello")); // false
console.log(isPalindrome("A man, a plan, a canal, Panama")); //
true

4. Write a JavaScript program to sort an array of numbers in


ascending order.
<!DOCTYPE html>
<html>
<head>
<title>Sort Array in Ascending Order</title>
</head>
<body>

<h1>Sort Array of Numbers</h1>

<label for="arrayInput">Enter numbers separated by


commas:</label><br>
<input type="text" id="arrayInput" placeholder="e.g.
12,5,8,130,44" size="30" />
<button onclick="sortArray()">Sort</button>

<h2>Sorted Array:</h2>
<p id="result"></p>

<script>
function sortArray() {
let input = document.getElementById('arrayInput').value;
if (!input) {
document.getElementById('result').textContent = "Please
enter some numbers.";
return;
}

// Convert input string to array of numbers


let arr = input.split(',').map(item => Number(item.trim()));

// Check for invalid numbers


if (arr.some(isNaN)) {
document.getElementById('result').textContent = "Invalid
input! Please enter only numbers separated by commas.";
return;
}

// Sort the array in ascending order


arr.sort(function(a, b) {
return a - b;
});

document.getElementById('result').textContent = arr.join(', ');


}
</script>

</body>
</html>

5. Define an array in JavaScript. How do you declare and


initialize it?
Array in JavaScript: Definition, Declaration, and Initialization
What is an Array?
An array in JavaScript is a special variable that can hold multiple
values at once. These values are stored in an ordered list and can be
accessed using their index (starting from 0).

How to Declare an Array?


You can declare an array in JavaScript in two main ways:
1. Using array literal syntax (most common and recommended):
let fruits = ["Apple", "Banana", "Cherry"];
2. Using the Array constructor:
let fruits = new Array("Apple", "Banana", "Cherry");

How to Initialize an Array?


• Initialization means assigning values to the array when declaring it.
• Example with initialization using array literal:
let numbers = [1, 2, 3, 4, 5];
• You can also declare an empty array and add values later:
let colors = [];
colors[0] = "Red";
colors[1] = "Green";
colors[2] = "Blue";

Summary:
• Arrays store multiple values in an ordered way.
• Declared with [] (array literal) or new Array().
• Access elements by their index, starting from 0.

6. Write a function `countVowels(str)` that counts vowels in a


string using loops and conditions.
function countVowels(str) {
let count = 0;
let vowels = "aeiouAEIOU";

for (let i = 0; i < str.length; i++) {


if (vowels.indexOf(str[i]) !== -1) {
count++;
}
}

return count;
}

// Example usage:
console.log(countVowels("Hello World")); // Output: 3
console.log(countVowels("JavaScript")); // Output: 3
console.log(countVowels("xyz")); // Output: 0

7. Write JavaScript code to loop through a string and print each


character on a new line

<!DOCTYPE html>
<html>
<head>
<title>Print Each Character</title>
</head>
<body>

<h1>Print Each Character of a String</h1>


<label for="inputString">Enter a string:</label><br>
<input type="text" id="inputString" size="30" />
<button onclick="printCharacters()">Print Characters</button>

<pre id="output"></pre>

<script>
function printCharacters() {
let str = document.getElementById('inputString').value;
let outputArea = document.getElementById('output');
outputArea.textContent = ""; // Clear previous output

for (let i = 0; i < str.length; i++) {


outputArea.textContent += str[i] + "\n";
}
}
</script>

</body>
</html>

8. Write a program to input 5 names into an array and sort them


alphabetically
<!DOCTYPE html>
<html>
<head>
<title>Sort Names Alphabetically</title>
</head>
<body>

<h1>Enter 5 Names</h1>

<div id="inputs">
<input type="text" id="name0" placeholder="Name 1"
/><br><br>
<input type="text" id="name1" placeholder="Name 2"
/><br><br>
<input type="text" id="name2" placeholder="Name 3"
/><br><br>
<input type="text" id="name3" placeholder="Name 4"
/><br><br>
<input type="text" id="name4" placeholder="Name 5"
/><br><br>
</div>

<button onclick="sortNames()">Sort Names</button>

<h2>Sorted Names:</h2>
<p id="result"></p>

<script>
function sortNames() {
let names = [];

// Collect names from input fields


for (let i = 0; i < 5; i++) {
let name = document.getElementById('name' + i).value.trim();
if (name === "") {
alert("Please enter all 5 names.");
return;
}
names.push(name);
}

// Sort names alphabetically (case-insensitive)


names.sort(function(a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});

// Display sorted names


document.getElementById('result').textContent = names.join(',
');
}
</script>

</body>
</html>
9. Write a JavaScript function to reverse a given string
<!DOCTYPE html>
<html>
<head>
<title>Reverse a String</title>
</head>
<body>
<h1>Reverse a String</h1>

<label for="inputString">Enter a string:</label><br>


<input type="text" id="inputString" size="30" />
<button onclick="reverseInput()">Reverse</button>

<h2>Reversed String:</h2>
<p id="result"></p>

<script>
function reverseString(str) {
return str.split('').reverse().join('');
}

function reverseInput() {
let str = document.getElementById('inputString').value;
let reversed = reverseString(str);
document.getElementById('result').textContent = reversed;
}
</script>

</body>
</html>
10.Explain how to define and call a function in JavaScript with an
example
Defining and Calling a Function in JavaScript
What is a Function?
A function is a reusable block of code designed to perform a
specific task. It helps organize code, avoid repetition, and make
programs modular.

How to Define a Function?


Use the function keyword followed by a name, parentheses (), and
curly braces {} containing the code:
function greet() {
console.log("Hello, world!");
}
• greet is the function name.
• The code inside {} runs when the function is called.
How to Call a Function?
Simply write the function name followed by parentheses:
greet(); // This will output: Hello, world!

Complete Example:
// Function definition
function greet() {
console.log("Hello, world!");
}

// Function call
greet();

6 Marks Questions:
\
1. Explain the string methods `length`, `charAt()`, `concat()`, and
`toUpperCase()` with examples.
Explanation of String Methods in JavaScript
1. length
• Returns the number of characters in a string.
• It’s a property, not a function, so no parentheses.
Example:
let str = "Hello";
console.log(str.length); // Output: 5

2. charAt(index)
• Returns the character at the specified index.
• Index starts at 0.
Example:
let str = "Hello";
console.log(str.charAt(1)); // Output: "e" (second character)

3. concat()
• Combines two or more strings and returns a new string.
• Takes strings as arguments.
Example:
let str1 = "Hello";
let str2 = "World";
let result = str1.concat(" ", str2);
console.log(result); // Output: "Hello World"

4. toUpperCase()
• Converts all characters in a string to uppercase.
• Returns a new string.
Example:
let str = "hello";
console.log(str.toUpperCase()); // Output: "HELLO"

2. Write a function `listPrimes(num)` that displays all prime


numbers less than a given number using loops and conditions.

<!DOCTYPE html>
<html>
<head>
<title>List Prime Numbers</title>
</head>
<body>

<h1>List Prime Numbers Less Than N</h1>

<label for="numberInput">Enter a number:</label><br>


<input type="number" id="numberInput" min="2"
placeholder="Enter a number greater than 1" />
<button onclick="displayPrimes()">Show Primes</button>

<h2>Prime Numbers:</h2>
<p id="result"></p>

<script>
function isPrime(n) {
if (n <= 1) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
function listPrimes(num) {
let primes = [];
for (let i = 2; i < num; i++) {
if (isPrime(i)) {
primes.push(i);
}
}
return primes;
}

function displayPrimes() {
const input = document.getElementById('numberInput').value;
const num = Number(input);
const resultArea = document.getElementById('result');

if (isNaN(num) || num < 2) {


resultArea.textContent = "Please enter a valid number greater
than 1.";
return;
}

const primes = listPrimes(num);

if (primes.length === 0) {
resultArea.textContent = "No prime numbers found less than "
+ num + ".";
} else {
resultArea.textContent = primes.join(', ');
}
}
</script>

</body>
</html>

3. Write a program to search a specific string in an array and


print its index.
<!DOCTYPE html>
<html>
<head>
<title>Search String in Array</title>
</head>
<body>

<h1>Search for a String in an Array</h1>

<label for="searchString">Enter string to search:</label><br>


<input type="text" id="searchString" placeholder="Enter string"
/>
<button onclick="searchStringInArray()">Search</button>

<h2>Result:</h2>
<p id="result"></p>

<script>
// Sample array of strings
const fruits = ["Apple", "Banana", "Cherry", "Date",
"Elderberry"];

function searchStringInArray() {
const searchStr =
document.getElementById('searchString').value.trim();
const resultArea = document.getElementById('result');

if (searchStr === "") {


resultArea.textContent = "Please enter a string to search.";
return;
}

// Search for the string in the array (case-sensitive)


const index = fruits.indexOf(searchStr);

if (index !== -1) {


resultArea.textContent = `"${searchStr}" found at index:
${index}`;
} else {
resultArea.textContent = `"${searchStr}" not found in the
array.`;
}
}
</script>

</body>
</html>
4. Write a JavaScript function that converts a given string to title
case (first letter capitalized for each word).
<!DOCTYPE html>
<html>
<head>
<title>Convert to Title Case</title>
</head>
<body>

<h1>Convert String to Title Case</h1>

<label for="inputString">Enter a string:</label><br>


<input type="text" id="inputString" size="40" />
<button onclick="convertToTitleCase()">Convert</button>

<h2>Title Case Result:</h2>


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

<script>
function toTitleCase(str) {
return str
.toLowerCase()
.split(' ')
.map(word => {
if (word.length === 0) return word; // Handle multiple
spaces
return word[0].toUpperCase() + word.slice(1);
})
.join(' ');
}

function convertToTitleCase() {
const input = document.getElementById('inputString').value;
const result = toTitleCase(input);
document.getElementById('result').textContent = result;
}
</script>

</body>
</html>

5. Create an array of objects containing product details (id, name,


price) and write code to filter products below a given price
<!DOCTYPE html>
<html>
<head>
<title>Filter Products by Price</title>
</head>
<body>

<h1>Filter Products Below a Given Price</h1>

<label for="priceInput">Enter maximum price:</label><br>


<input type="number" id="priceInput" min="0"
placeholder="Enter price" />
<button onclick="filterProducts()">Filter</button>

<h2>Filtered Products:</h2>
<ul id="productList"></ul>

<script>
// Array of product objects
const products = [
{ id: 1, name: "Laptop", price: 1200 },
{ id: 2, name: "Smartphone", price: 800 },
{ id: 3, name: "Tablet", price: 400 },
{ id: 4, name: "Headphones", price: 150 },
{ id: 5, name: "Smartwatch", price: 200 }
];

function filterProducts() {
const maxPriceInput =
document.getElementById('priceInput').value;
const maxPrice = Number(maxPriceInput);
const productList = document.getElementById('productList');

productList.innerHTML = ""; // Clear previous list

if (isNaN(maxPrice) || maxPrice < 0) {


alert("Please enter a valid non-negative number for price.");
return;
}

// Filter products below maxPrice


const filtered = products.filter(product => product.price <
maxPrice);
if (filtered.length === 0) {
productList.innerHTML = "<li>No products found below this
price.</li>";
return;
}

// Display filtered products


filtered.forEach(product => {
const li = document.createElement('li');
li.textContent = `ID: ${product.id}, Name: ${product.name},
Price: $${product.price}`;
productList.appendChild(li);
});
}
</script>

</body>
</html>

6. Develop a program using an array to store marks of students


and calculate average, highest, and lowest marks.
<!DOCTYPE html>
<html>
<head>
<title>Student Marks Statistics</title>
</head>
<body>

<h1>Student Marks Analysis</h1>

<label for="marksInput">Enter marks separated by commas (e.g.,


85, 90, 78):</label><br>
<input type="text" id="marksInput" size="50"
placeholder="Enter marks" />
<button onclick="calculateStats()">Calculate</button>

<h2>Results:</h2>
<p id="average"></p>
<p id="highest"></p>
<p id="lowest"></p>

<script>
function calculateStats() {
const input = document.getElementById('marksInput').value;
const marksStrArray = input.split(',').map(item => item.trim());
const marks = [];

for (let val of marksStrArray) {


let num = Number(val);
if (isNaN(num) || num < 0 || num > 100) {
alert("Please enter valid marks between 0 and 100.");
return;
}
marks.push(num);
}

if (marks.length === 0) {
alert("Please enter at least one mark.");
return;
}

// Calculate average
let sum = 0;
let highest = marks[0];
let lowest = marks[0];

for (let mark of marks) {


sum += mark;
if (mark > highest) highest = mark;
if (mark < lowest) lowest = mark;
}

const average = (sum / marks.length).toFixed(2);

document.getElementById('average').textContent = `Average
Mark: ${average}`;
document.getElementById('highest').textContent = `Highest
Mark: ${highest}`;
document.getElementById('lowest').textContent = `Lowest
Mark: ${lowest}`;
}
</script>

</body>
</html>
7. Explain the following array methods with examples: push(),
pop(), toString(), sort(), shift(), unshift(), join(), concat()
Detailed Explanation of JavaScript Array Methods with Examples
1. push()
• Purpose: Adds one or more elements to the end of an array.
• Returns: The new length of the array.
• Use case: When you want to append data to an existing array.
Example:
let fruits = ["Apple", "Banana"];
fruits.push("Orange"); // Adds "Orange" at the end
console.log(fruits); // Output: ["Apple", "Banana", "Orange"]

2. pop()
• Purpose: Removes the last element from an array.
• Returns: The removed element.
• Use case: When you want to remove the most recently added item or
work with the last element.
Example:
let fruits = ["Apple", "Banana", "Orange"];
let lastFruit = fruits.pop(); // Removes "Orange"
console.log(lastFruit); // Output: "Orange"
console.log(fruits); // Output: ["Apple", "Banana"]

3. toString()
• Purpose: Converts the entire array into a comma-separated string.
• Returns: A string representing the array elements.
• Use case: When you need to display or store the array as a string.
Example:
let numbers = [1, 2, 3];
console.log(numbers.toString()); // Output: "1,2,3"

4. sort()
• Purpose: Sorts the elements of the array in place and returns the sorted
array.
• Default Behavior: Sorts elements as strings in ascending lexicographical
order.
• Use case: To organize data alphabetically or numerically (with a compare
function).
Example:
let letters = ["b", "a", "c"];
letters.sort();
console.log(letters); // Output: ["a", "b", "c"]

let numbers = [40, 1, 5, 200];


// Default sort treats numbers as strings, so use a compare function:
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 5, 40, 200]

5. shift()
• Purpose: Removes the first element of an array.
• Returns: The removed element.
• Use case: When you want to remove items from the front of the array
(like a queue).
Example:
let queue = ["First", "Second", "Third"];
let firstItem = queue.shift();
console.log(firstItem); // Output: "First"
console.log(queue); // Output: ["Second", "Third"]

6. unshift()
• Purpose: Adds one or more elements to the beginning of an array.
• Returns: The new length of the array.
• Use case: When you want to add items to the front of an array.
Example:
let queue = ["Second", "Third"];
queue.unshift("First");
console.log(queue); // Output: ["First", "Second", "Third"]

7. join()
• Purpose: Joins all elements of an array into a string, separated by a
specified separator.
• Returns: A string.
• Use case: To create a string from array elements with a custom separator.
Example:
let words = ["Hello", "World"];
console.log(words.join(" ")); // Output: "Hello World"
console.log(words.join("-")); // Output: "Hello-World"

8. concat()
• Purpose: Merges two or more arrays and returns a new array without
changing the existing arrays.
• Use case: When you want to combine arrays.
Example:
let arr1 = [1, 2];
let arr2 = [3, 4];
let combined = arr1.concat(arr2);
console.log(combined); // Output: [1, 2, 3, 4]

// Original arrays remain unchanged


console.log(arr1); // Output: [1, 2]
console.log(arr2); // Output: [3, 4]

You might also like