Javascript
Javascript
<html>
<head>
</head>
<body>
<ul id="even-numbers"></ul>
<script>
// Get reference to the HTML element where we'll show the numbers
// Loop from 1 to 10
if (i % 2 === 0) {
listItem.textContent = i;
list.appendChild(listItem);
}
}
</script>
</body>
</html>
1. if Statement
Syntax:
if (condition) {
Example:
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) {
} else {
Example:
let age = 16;
} else {
3. switch Statement
Use when: You need to compare one value against multiple possible values (especially for
discrete choices).
Syntax:
switch(expression) {
case value1:
break;
case value2:
break;
default:
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");
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.
• 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.
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).
Server-Side:
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}`);
}
};
// 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);
//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
<html>
<head>
</head>
<body>
<h2 id="result"></h2>
<script>
function findLargest() {
let largest;
return;
largest = num1;
largest = num2;
} else {
largest = num3;
</script>
</body>
</html>
<h2 id="result"></h2>
<script>
function checkEvenOdd() {
// Get input value and convert it to a number
let num = parseInt(document.getElementById("number").value);
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2 id="result"></h2>
<script>
function checkDay() {
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:
</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>
</head>
<body>
<h2 id="result"></h2>
<script>
function findLargest() {
return;
let largest;
largest = num1;
} else {
largest = num3;
} else {
largest = num2;
} else {
largest = num3;
</script>
</body>
</html>
9. Demonstrate how to declare and access object properties using dot notation.
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
};
10. Develop a program to demonstrate the use of `for...in` loop to iterate through object
properties.
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 = {
year: 1988
};
6 Marks Questions:
Theory:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="checkPrime()">Check</button>
<h2 id="result"></h2>
<script>
function checkPrime() {
let num =
parseInt(document.getElementById('numberInput').value);
return;
if (num === 1) {
return;
if (num % i === 0) {
isPrime = false;
// Display result
if (isPrime) {
} else {
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table</title>
</head>
<body>
<pre id="result"></pre>
<script>
function printTable() {
if (isNaN(num)) {
return;
document.getElementById('result').textContent = output;
console.log(output);
}
</script>
</body>
</html>
1. Arithmetic Operators
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;
3. Logical Operators
Example:
let a = 5, b = 10;
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;
},
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.
<h1>Calculate Factorial</h1>
<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;
// Example usage:
console.log(isPalindrome("Madam")); // true
console.log(isPalindrome("Hello")); // false
console.log(isPalindrome("A man, a plan, a canal, Panama")); //
true
<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;
}
</body>
</html>
Summary:
• Arrays store multiple values in an ordered way.
• Declared with [] (array literal) or new Array().
• Access elements by their index, starting from 0.
return count;
}
// Example usage:
console.log(countVowels("Hello World")); // Output: 3
console.log(countVowels("JavaScript")); // Output: 3
console.log(countVowels("xyz")); // Output: 0
<!DOCTYPE html>
<html>
<head>
<title>Print Each Character</title>
</head>
<body>
<pre id="output"></pre>
<script>
function printCharacters() {
let str = document.getElementById('inputString').value;
let outputArea = document.getElementById('output');
outputArea.textContent = ""; // Clear previous output
</body>
</html>
<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>
<h2>Sorted Names:</h2>
<p id="result"></p>
<script>
function sortNames() {
let names = [];
</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>
<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.
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"
<!DOCTYPE html>
<html>
<head>
<title>List Prime Numbers</title>
</head>
<body>
<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 (primes.length === 0) {
resultArea.textContent = "No prime numbers found less than "
+ num + ".";
} else {
resultArea.textContent = primes.join(', ');
}
}
</script>
</body>
</html>
<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');
</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>
<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>
<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');
</body>
</html>
<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 = [];
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];
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"]
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]