JS Practiced Examples

HTML
CSS
C#
SQL

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

  • Prime numbers between two numbers
  • Convert Kilometers to Miles
  • Find the Square Root
  • Swap Two Variables
  • Find the Largest Among Three Numbers
  • String is Palindrome or Not
  • Count the Number of Vowels in a String
  • Merge Properties of Two Objects
  • Random Item From an Array
  • Append an Object to an Array
  • Remove All Whitespaces From a Text
  • Remove duplicate values From an Array
  • String Starts and Ends With Certain Char
  • Check Leap Year
  • Replace All Line Breaks
  • Compare Elements of Two Arrays
  • Split the Array into Smaller Chunks
  • Validate an Email Address
  • Password Toggle Functionality
  • Dynamic JavaScript Calculator

Write a JavaScript program that takes two numbers as input from the user and then prints all the prime numbers between those two numbers.

1. Take input from the users: Ask the user to enter two numbers. These two numbers will define the range between which you want to find prime numbers.
2. Find Prime Numbers: A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. So, you need to check for each number in the given range whether it is prime or not.
3. Print Prime Numbers: If a number is prime, print it.
Example: Let's say the user enters 5 and 15.
- Check each number from 5 to 15.
- Print the prime numbers in this range.

Here's a simple example in JavaScript:


// Function to check if a number is prime
function isPrime(num) {
if (num <= 1) return false;

for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}

// Take input from the users
let startNumber = parseInt(prompt("Enter the starting number:"));
let endNumber = parseInt(prompt("Enter the ending number:"));

// Print prime numbers between the given range
console.log(`Prime numbers between ${startNumber} and ${endNumber}:`);
for (let i = startNumber; i <= endNumber; i++) {
if (isPrime(i)) {
console.log(i);
}
}
Output

Write a JavaScript program that takes a distance in kilometers as input from the user and converts it to miles.

1. Take input from the user: Ask the user to enter a distance in kilometers. This will be the value you want to convert to miles.
2. Conversion from Kilometers to Miles: 1 kilometre is approximately equal to 0.621371 miles. To convert kilometers to miles, you multiply the distance in kilometers by this conversion factor.
3. Display the Result: Print or display the converted distance in miles.
Example: Let's say the user enters 10 kilometers.
- Convert 10 kilometers to miles using the conversion factor: 10 km * 0.621371 miles/km ≈ 6.21371 miles.

Here's a simple example in JavaScript:

// Take input from the user
let kilometers = parseFloat(prompt("Enter the distance in kilometers:"));

// Conversion factor from kilometers to miles
const conversionFactor = 0.621371;

// Convert kilometers to miles
let miles = kilometers * conversionFactor;

// Display the result
console.log(`${kilometers} kilometers is approximately ${miles.toFixed(2)} miles.`);
Output

Write a JavaScript program that takes a number as input from the user and calculates its square root.

1. Take input from the user: Ask the user to enter a number. This will be the value for which you want to find the square root.
2. Calculate Square Root: Use the Math.sqrt() function in JavaScript to find the square root of the entered number.
3. Display the Result: Print or display the calculated square root.
Example: Let's say the user enters 25.
- The square root of 25 is 5, because 5 * 5 = 25.

Here's a simple example in JavaScript:

// Take input from the user
let number = parseFloat(prompt("Enter a number to find its square root:"));

// Check if the entered number is non-negative
if (number >= 0) {
    // Calculate the square root
    let squareRoot = Math.sqrt(number);

    // Display the result
    console.log(`The square root of ${number} is approximately ${squareRoot.toFixed(2)}.`);
} else {
    console.log("Please enter a non-negative number for square root calculation.");
}
Output


In this code:
- The user is prompted to enter a number.
- The program then checks if the entered number is non-negative because the square root is not defined for negative numbers.
- If the number is non-negative, the square root is calculated and displayed. The toFixed(2) is used to round the result to two decimal places for better readability.
- If the entered number is negative, a message is displayed to inform the user to enter a non-negative number.

Write a JavaScript program that takes two variables as input from the user and swaps their values using different methods.

1. Using a Temporary Variable: Use a third variable to temporarily store the value of one variable, then swap the values of the two variables.
2. Using ES6 (ES2015) Destructuring Assignment: Use the destructuring assignment syntax to swap the values of the two variables directly.
3. Using Arithmetic Operators: Add and subtract the values of the two variables to swap their values without using a temporary variable.
4. Using Bitwise XOR Operator: Use the bitwise XOR (^) operator to swap the values of the two variables without using a temporary variable.
Example: Let's say the user enters a = 5 and b = 10.
- After swapping, a should be 10 and b should be 5.

Here's a simple example in JavaScript:

// Take input from the users
let a = parseFloat(prompt("Enter the value of variable a:"));
let b = parseFloat(prompt("Enter the value of variable b:"));

// 1. Using a Temporary Variable
let temp = a;
a = b;
b = temp;
console.log(`Using a Temporary Variable: a = ${a}, b = ${b}`);

// 2. Using ES6 Destructuring Assignment
[b, a] = [a, b];
console.log(`Using Destructuring Assignment: a = ${a}, b = ${b}`);

// 3. Using Arithmetic Operators
a = a + b;
b = a - b;
a = a - b;
console.log(`Using Arithmetic Operators: a = ${a}, b = ${b}`);

// 4. Using Bitwise XOR Operator
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log(`Using Bitwise XOR Operator: a = ${a}, b = ${b}`);
Output

Write a JavaScript program that takes three numbers as input from the user and finds the largest among them using two different methods.

1. Using if...else Statement: Compare the three numbers using if...else statements to determine which one is the largest.
2. Using Math.max(): Utilize the Math.max() function in JavaScript, which takes multiple arguments and returns the largest one.
Example: Let's say the user enters a = 7, b = 15, and c = 10.
- The program should find that the largest among these three is b = 15.

Here's a simple example in JavaScript:

// Take input from the users
let a = parseFloat(prompt("Enter the first number:"));
let b = parseFloat(prompt("Enter the second number:"));
let c = parseFloat(prompt("Enter the third number:"));

// 1. Using if...else Statement
let largestIfElse;
if (a >= b && a >= c) {
    largestIfElse = a;
} else if (b >= a && b >= c) {
    largestIfElse = b;
} else {
    largestIfElse = c;
}
console.log(`Using if...else Statement: The largest number is ${largestIfElse}`);

// 2. Using Math.max()
let largestMathMax = Math.max(a, b, c);
console.log(`Using Math.max(): The largest number is ${largestMathMax}`);
Output

Write a JavaScript program that checks whether a given string is a palindrome or not.

1. Palindrome Definition: A palindrome is a word, phrase, or sequence of characters that reads the same backwards as forward.
2. Check for Palindrome: Compare the characters from the beginning and the end of the string to determine if they read the same in both directions.
Example: Let's say the user enters the string "radar".
- The program should recognize that "radar" is a palindrome because it reads the same backwards.

Here's a simple example in JavaScript:

// Function to check if a string is a palindrome
function isPalindrome(str) {
    // Remove non-alphanumeric characters and convert to lowercase for comparison
    const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
    
    // Compare characters from the beginning and end of the string
    for (let i = 0; i < cleanStr.length / 2; i++) {
        if (cleanStr[i] !== cleanStr[cleanStr.length - 1 - i]) {
            return false;
        }
    }
    return true;
}

// Take input from the user
let userInput = prompt("Enter a string to check if it's a palindrome:");

// Check if the entered string is a palindrome
if (isPalindrome(userInput)) {
    console.log(`"${userInput}" is a palindrome.`);
} else {
    console.log(`"${userInput}" is not a palindrome.`);
}
Output

Write a JavaScript program that takes a string as input from the user and counts the number of vowels in that string using a for loop.

1. Vowels Definition: Vowels are the letters 'a', 'e', 'i', 'o', and 'u' (both lowercase and uppercase).
2. Count Vowels Using a for Loop:
- Iterate through each character in the string using a for loop.
- Check if each character is a vowel, and if so, increment a counter.
Example: Let's say the user enters the string "Hello".
- The program should count the vowels ('e' and 'o') and display that there are 2 vowels in the string.

Here's a simple example in JavaScript:

// Function to count the number of vowels in a string
function countVowels(str) {
    // Initialize the counter
    let vowelCount = 0;
    
    // Convert the string to lowercase for case-insensitive comparison
    const lowerCaseStr = str.toLowerCase();
    
    // Iterate through each character in the string
    for (let i = 0; i < str.length; i++) {
        // Check if the character is a vowel
        if ('aeiou'.includes(lowerCaseStr[i])) {
            vowelCount++;
        }
    }
    
    return vowelCount;
}

// Take input from the user
let userInput = prompt("Enter a string to count the number of vowels:");

// Count the number of vowels in the entered string
let result = countVowels(userInput);

// Display the result
console.log(`The number of vowels in "${userInput}" is: ${result}`);
Output

Write a JavaScript program that merges the properties of two objects using different methods: Object.assign() and the spread operator.

1. Using Object.assign(): The Object.assign() method is used to copy the values of all enumerable properties from one or more source objects to a target object.
2. Using Spread Operator: The spread operator (...) is used to create a shallow copy of an object or to merge the properties of multiple objects into a new object.
Example: Let's say you have two objects:
- const person = { name: 'Johnson', age: 26 };
- const student = { gender: 'male' };
- The program should merge these two objects, resulting in { name: 'Johnson', age: 26, gender: 'male' }.

Here's a simple example in JavaScript:

// Objects to be merged
const person = { name: 'Johnson', age: 26 };
const student = { gender: 'male' };

// 1. Using Object.assign()
const mergedObjectAssign = Object.assign({}, person, student);
console.log('Using Object.assign():', mergedObjectAssign);

// 2. Using Spread Operator
const mergedSpreadOperator = { ...person, ...student };
console.log('Using Spread Operator:', mergedSpreadOperator);
Output

Write a JavaScript program that retrieves a random item from an array.

1. Random Selection: To get a random item from an array, we need to generate a random index within the range of the array's length.
2. Retrieve Item: Once we have a random index, we can use it to access the item at that index in the array.
Example: Let's say we have an array: [1, 'Iqra', 2, 3, 4, 5, 8].
- The program should randomly select one item from this array, for example, it might select 'Iqra'.

Here's a simple example in JavaScript:

// Array to get a random item from
const array = [1, 'Iqra', 2, 3, 4, 5, 8];

// Function to get a random item from an array
function getRandomItemFromArray(arr) {
    // Generate a random index within the range of the array's length
    const randomIndex = Math.floor(Math.random() * arr.length);
    
    // Return the item at the randomly generated index
    return arr[randomIndex];
}

// Get a random item from the array
const randomItem = getRandomItemFromArray(array);

// Display the randomly selected item
console.log('Randomly selected item:', randomItem);
Output

Write a JavaScript program that appends an object to an array using three different methods: push(), splice(), and the spread operator.

1. Using push(): The push() method adds one or more elements to the end of an array.
2. Using splice(): The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
3. Using Spread Operator: The spread operator (...) can be used to create a new array by combining the elements of one or more arrays and additional items.
Example: Let's say we have an array [1, 3, 5, 7] and an object {x: 12, y: 8}.
- The program should append the object to the array, resulting in [1, 3, 5, 7, {x: 12, y: 8}].

Here's a simple example in JavaScript:

// Array and object to append
const array = [1, 3, 5, 7];
const object = {x: 12, y: 8};

// 1. Using push()
const arrayPush = [...array]; // Create a copy of the array
arrayPush.push(object);
console.log('Using push():', arrayPush);

// 2. Using splice()
const arraySplice = [...array]; // Create a copy of the array
arraySplice.splice(arraySplice.length, 0, object);
console.log('Using splice():', arraySplice);

// 3. Using Spread Operator
const arraySpreadOperator = [...array, object];
console.log('Using Spread Operator:', arraySpreadOperator);
Output

Write a JavaScript program that removes all whitespaces from a given text using two different methods: split() and join(), and using regular expressions.

1. Using split() and join():
- The split() method is used to split a string into an array of substrings based on a specified separator.
- The join() method is used to join all elements of an array into a string.
2. Using Regular Expression: Regular expressions provide a powerful way to perform pattern matching and manipulation of strings.
Example: Let's say we have a string ' Hello World '.
- The program should remove all whitespaces from this string, resulting in 'HelloWorld'.

Here's a simple example in JavaScript:

// Input string with whitespaces
const string = '      Hello World      ';

// 1. Using split() and join()
const stringWithoutWhitespaceSplitJoin = string.split(' ').join('');
console.log('Using split() and join():', stringWithoutWhitespaceSplitJoin);


// 2. Using Regular Expression
const stringWithoutWhitespaceRegex = string.replace(/\s/g, '');
console.log('Using Regular Expression:', stringWithoutWhitespaceRegex);
Output

Write a JavaScript program that removes duplicate values from an array using two different methods: using indexOf() and push(), and using Set.

1. Using indexOf() and push(): Iterate through the array and keep track of unique elements using another array and the indexOf() method.
2. Using Set: Utilize the Set object in JavaScript, which allows you to store unique values of any type.
Example: Let's say we have an array [1, 2, 3, 2, 3].
- The program should remove the duplicate values from this array, resulting in [1, 2, 3].

Here's a simple example in JavaScript:

// Array with duplicate values
const array = [1, 2, 3, 2, 3];

// 1. Using indexOf() and push()
const uniqueArrayIndexOfPush = [];
array.forEach(element => {
    if (uniqueArrayIndexOfPush.indexOf(element) === -1) {
        uniqueArrayIndexOfPush.push(element);
    }
});
console.log('Using indexOf() and push():', uniqueArrayIndexOfPush);

// 2. Using Set
const uniqueArraySet = [...new Set(array)];
console.log('Using Set:', uniqueArraySet);
Output

Write a JavaScript program that checks whether a given string starts and ends with certain characters using two different methods: using built-in methods and using regular expressions (regex).

1. Using Built-in Methods: Utilize the startsWith() and endsWith() methods available for strings in JavaScript.
2. Using Regex: Create a regular expression pattern to match the required starting and ending characters of the string.
Example: Let's say we have a string 'hello world' and we want to check if it starts with 'hello' and ends with 'world'.
- The program should return true for both methods.

Here's a simple example in JavaScript:

// Input string
const string = 'hello world';

// Starting and ending characters
const startsWithChar = 'hello';
const endsWithChar = 'world';

// 1. Using Built-in Methods
const startsWithAndEndsWithBuiltIn = string.startsWith(startsWithChar)
 && string.endsWith(endsWithChar);
console.log('Using Built-in Methods:', startsWithAndEndsWithBuiltIn);

// 2. Using Regex
const regexPattern = new RegExp(`^${startsWithChar}.*${endsWithChar}$`);
const startsWithAndEndsWithRegex = regexPattern.test(string);
console.log('Using Regex:', startsWithAndEndsWithRegex);
Output

Write a JavaScript program that checks whether a given year is a leap year using two different methods: using if...else statements and using the Date object.

1. Using if...else: A leap year is a year that is divisible by 4 and not divisible by 100, unless it is also divisible by 400. We'll use these conditions to determine if the year is a leap year.
2. Using new Date(): We can create a new Date object in JavaScript and set its year to the input year. Then we'll check if February 29 exists in that year.
Example: Let's say the user enters the year 2024.
- The program should determine that 2024 is a leap year.

Here's a simple example in JavaScript:

// Function to check if a year is a leap year using if...else
function isLeapYearIfElse(year) {
    if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
        return true;
    } else {
        return false;
    }
}

// Function to check if a year is a leap year using new Date()
function isLeapYearDate(year) {
    const date = new Date(year, 1, 29); // February 29
    return date.getDate() === 29;
}

// Take input from the user
const year = parseInt(prompt("Enter a year to check if it's a leap year:"));

// Check if the entered year is a leap year using both methods
const isLeapIfElse = isLeapYearIfElse(year);
const isLeapDate = isLeapYearDate(year);

// Display the results
console.log(`Using if...else: ${year} is a leap year? ${isLeapIfElse}`);
console.log(`Using new Date(): ${year} is a leap year? ${isLeapDate}`);
Output

Write a JavaScript program that replaces all line breaks in a string with a break tag using two different methods: using regular expressions (regex) and using built-in methods (split and join).

1. Using RegEx: Regular expressions can be used to match patterns in strings. We'll use the (\n) character to match line breaks in the string and replace them with break tag.
2. Using Built-in Methods: We can split the string into an array of substrings using the split() method with '\n' as the separator. Then we'll join the array back into a string using the join() method with '
' as the separator.
Example: Let's say we have a string:

 "Hello
   World!"
- The program should replace the line break between "Hello" and "World!" with a break tag.

Here's a simple example in JavaScript:

// Input string with line breaks
const inputString = `Hello
World!`;

// 1. Using RegEx
const stringWithBrRegex = inputString.replace(/\n/g, '
'); console.log('Using RegEx:', stringWithBrRegex); // 2. Using Built-in Methods (split and join) const stringWithBrBuiltIn = inputString.split('\n').join('
'); console.log('Using Built-in Methods (split and join):', stringWithBrBuiltIn);
Output

Write a JavaScript program that compares elements of two arrays using a for loop.

- We'll iterate over each element of the arrays using a for loop and compare the elements at corresponding indices.
- If the arrays have the same length and all corresponding elements are equal, then the arrays are considered equal.
Example: Let's say we have two arrays:

array1 = [1, 3, 4, 5, 6, 8]
array2 = [1, 3, 4, 5, 6, 8]
- The program should determine that both arrays are equal.

Here's a simple example in JavaScript:

// Arrays to compare
const array1 = [1, 3, 4, 5, 6, 8];
const array2 = [1, 3, 4, 5, 6, 8];

// Function to compare elements of two arrays using 'for' loop
function compareArrays(arr1, arr2) {
    // Check if both arrays have the same length
    if (arr1.length !== arr2.length) {
        return false;
    }
    
    // Iterate over each element of the arrays
    for (let i = 0; i < arr1.length; i++) {
        // Compare elements at corresponding indices
        if (arr1[i] !== arr2[i]) {
            return false; // If any element is not equal, return false
        }
    }
    
    return true; // If all elements are equal, return true
}

// Check if the arrays are equal
const isEqual = compareArrays(array1, array2);

// Display the result
if (isEqual) {
    console.log('Arrays are equal.');
} else {
    console.log('Arrays are not equal.');
}
Output

Write a JavaScript program that splits an array into smaller chunks using two different methods: using slice() and using splice().

1. Using slice(): The slice() method extracts a section of the array and returns a new array without modifying the original array. We can use this method to split the array into smaller chunks.
2. Using splice(): The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. We can use this method to split the array into smaller chunks by removing elements from the original array.
Example: Let's say we have an array [1, 2, 3, 4, 5, 6, 7, 8] and we want to split it into chunks of size 2.
- The program should split the array into chunks [ [1, 2], [3, 4], [5, 6], [7, 8] ].

Here's a simple example in JavaScript:

// Function to split the array into smaller chunks using slice()
function splitArraySlice(arr, chunkSize) {
    const chunks = [];
    for (let i = 0; i < arr.length; i += chunkSize) {
        chunks.push(arr.slice(i, i + chunkSize));
    }
    return chunks;
}

// Function to split the array into smaller chunks using splice()
function splitArraySplice(arr, chunkSize) {
    const chunks = [];
    while (arr.length) {
        chunks.push(arr.splice(0, chunkSize));
    }
    return chunks;
}

// Input array and chunk size
const array = [1, 2, 3, 4, 5, 6, 7, 8];
const chunkSize = 2;

// Split the array into smaller chunks using both methods
const chunksSlice = splitArraySlice(array, chunkSize);
const chunksSplice = splitArraySplice(array.slice(), chunkSize); 
// Make a copy of the original array

// Display the results
console.log('Using slice():', chunksSlice);
console.log('Using splice():', chunksSplice);
Output

Write a JavaScript program to validate an email address. The email address should follow a basic format.

1. Basic Format: An email address typically consists of two parts: a local part and a domain part separated by an "@" symbol. For example, in "example123@gmail.com", "example123" is the local part and "gmail.com" is the domain part.
2. Validation Criteria:
- The local part can contain alphanumeric characters, periods ".", underscores "_", and hyphens "-".
- The domain part can contain alphanumeric characters and periods ".".
- The domain part must have at least one period and must have at least two characters after the last period (e.g., "com", "org").
3. JavaScript Program: We'll use regular expressions (regex) to check if the email address matches the desired format.
Example: Let's say we have an email address "example123@gmail.com".
- The program should validate that this email address follows the basic format.

Here's a simple example in JavaScript:

// Function to validate an email address
function validateEmail(email) {
    // Regular expression pattern for basic email format validation
    const pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return pattern.test(email);
}

// Email address to validate
const emailAddress = "example123@gmail.com";

// Validate the email address
const isValidEmail = validateEmail(emailAddress);

// Display the result
if (isValidEmail) {
    console.log(`"${emailAddress}" is a valid email address.`);
} else {
    console.log(`"${emailAddress}" is not a valid email address.`);
}
Output

Write a JavaScript code to create a password toggle functionality. This means allowing users to click on an eye icon to toggle the visibility of the password input field between hidden and visible.

1. Password Input Field: A password input field in HTML hides the characters typed by the user for security purposes.
2. Toggle Functionality:
- We'll add an eye icon next to the password input field.
- When the user clicks on the eye icon, we'll change the type of the input field from "password" to "text" and vice versa.
Example: Let's say we have a password input field and an eye icon. Initially, the password field is hidden. When the user clicks on the eye icon, the password should become visible, and when clicked again, it should become hidden again.

Here's a simple example in JavaScript:


/* Style for eye icon */
.password-toggle {
  cursor: pointer;
}

Output

Create a dynamic JavaScript calculator using HTML, CSS, and JavaScript. This calculator should be able to perform basic arithmetic operations such as addition, subtraction, multiplication, and division.

1. HTML Structure: We'll create the necessary HTML elements for the calculator, such as buttons for numbers and operations, and an input field to display the result.
2. CSS Styling: We'll add styles to make the calculator visually appealing and user-friendly.
3. JavaScript Functionality:
- We'll write JavaScript functions to handle user input, perform calculations, and update the display accordingly.
- Each button click will trigger a corresponding action, such as appending a number to the input field or performing an operation.
- The result of the calculation will be displayed in the input field.
Example: Let's say we create a calculator with buttons for numbers (0-9), decimal points, and basic arithmetic operations (+, -, *, /). When the user clicks on the buttons, the corresponding actions will be performed, and the result will be displayed in the input field.
1. Create an HTML file with the necessary structure for the calculator, including buttons and an input field.
2. Style the calculator using CSS to make it visually appealing.
3. Write JavaScript functions to handle button clicks, perform calculations, and update the display.
4. Test the calculator to ensure it works correctly for different inputs and operations.

Here's a simple example in JavaScript:

HTML Code

CSS Code


body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
}

.calculator {
    width: 300px;
    margin: 50px auto;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    padding: 20px;
}

.calculator input {
    width: calc(100% - 10px);
    margin-bottom: 10px;
    padding: 10px;
    font-size: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
}

button {
    padding: 10px;
    font-size: 18px;
    background-color: #4caf50;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #45a049;
}

button:active {
    background-color: #39843d;
}

JavaScript Code

// Function to handle button clicks
function buttonClick(value) {
    document.getElementById("result").value += value;
}

// Function to clear the input field
function clearInput() {
    document.getElementById("result").value = "";
}

// Function to calculate the result
function calculate() {
    try {
        const result = eval(document.getElementById("result").value);
        document.getElementById("result").value = result;
    } catch (error) {
        document.getElementById("result").value = "Error";
    }
}
Output