JavaScript Q&A Collection: Mastering Concepts

Welcome to the JavaScript Q&A Collection! This resource is designed to provide practical exercises and solutions to enhance your understanding of JavaScript concepts. Each question is followed by a detailed explanation or code snippet to aid comprehension and application.


Explore the JavaScript Problem Set PDF - a consolidated collection of questions, spanning different JavaScript concepts. Dive into a wide spectrum of topics, from basic loops to complex conditional statements, all neatly organized for easy reference. Whether you're just starting or aiming to enhance your JavaScript skills, this resource-packed PDF offers a wealth of exercises to amplify your understanding.

Checkout PDF
of chapter 31 - 40 ↓


Explore the index below to navigate to specific topics:

  1. Chapter 31 - 34 (Date & Time)
  2. Chapter 35 - 37 (Functions)
  3. Chapter 38 (Local vs Global Variables)
  4. Chapter 39 - 40 (Switch Statements)

Chapter 31 - 34: Date & Time

Chapter 31 - 34: Question 1

Q1. Code a statement that creates a new Date object and assigns it to dObj, which hasn't been declared beforehand.

Answer 1:

let dObj = new Date();
Chapter 31 - 34: Question 2

Q2. Code a statement that creates a new Date object, converts it to a string, and assigns the string to dStr, which hasn't been declared beforehand.

Answer 2:

let dStr = new Date().toString();
Chapter 31 - 34: Question 3

Q3. Code a statement that extracts the day of the week from a Date object represented by d and assigns it to day, which hasn't been declared beforehand.

Answer 3:

let d = new Date();
let day = d.getDay();
Chapter 31 - 34: Question 4

Q4. The day has been extracted from the Date object and assigned to d. The names of the days of the week have been assigned to the array dayNames. Alert the current day with array index.

Answer 4:

let d = new Date();
let dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let currentDayIndex = d.getDay();
let currentDayName = dayNames[currentDayIndex];

alert(currentDayName);
Chapter 31 - 34: Question 5

Q5. Extract all parts of the Date and Time and assign it to the variable which has not been declared beforehand.

Answer 5:

let currentDate = new Date();  

let year = currentDate.getFullYear();
let month = currentDate.getMonth();
let date = currentDate.getDate();
let day = currentDate.getDay();
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let seconds = currentDate.getSeconds();
let seconds = currentDate.getMilliseconds();
Chapter 31 - 34: Question 6

Q6. Code a statement that creates a Date object for the last day of the last month of 2020 and assigns it to later, which hasn't been declared beforehand.

Answer 6:

let later = new Date(2020, 11, 31);
Chapter 31 - 34: Question 7

Q7. Create a Date object for the second day of the second month of 1992 and assign it to a variable that hasn't been declared beforehand.

Answer 7:

let specificDate = new Date(1992, 1, 2);
Chapter 31 - 34: Question 8

Q8. Code a single statement that displays in an alert the milliseconds that elapsed between the reference date and the beginning of 1980.

Answer 8:

alert(new Date().getTime() - new Date(1980, 0, 1).getTime());
Chapter 31 - 34: Question 9

Q9. How do you change the year of a date in JavaScript?

Answer 9:

let myDate = new Date();
myDate.setFullYear(2023);
Chapter 31 - 34: Question 10

Q10. Write a JavaScript function to change the month of a given date to January.

Answer 10:

function changeMonthToJanuary(date) {
    date.setMonth(0); // January = index 0
    return date; // Returns the modified date
}

// Example usage:
var currentDate = new Date(); // Gets the current date
var dateInJanuary = changeMonthToJanuary(currentDate);
console.log(dateInJanuary);
Chapter 31 - 34: Question 11

Q11. What is the method to change the day of the week for a specific date in JavaScript?

Answer 11:

function changeDayOfWeek(date, newDayOfWeek) {
    var currentDayOfWeek = date.getDay(); // Get the current day of the week (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
    var difference = newDayOfWeek - currentDayOfWeek;
    date.setDate(date.getDate() + difference); // Adds the difference to the current day of the month
    return date;
}

// Example usage:
var currentDate = new Date();
var newDate = changeDayOfWeek(currentDate, 5); // Change the day of the week to Friday (0 = Sunday, 1 = Monday, ..., 6 = Saturday)
console.log(newDate);
Chapter 31 - 34: Question 12

Q12. Write a JavaScript function to change the minutes of a given time to a specific value. (Value by prompt)

Answer 12:

function changeMinutesToSpecificValue(time) {
    // Split the time string into hours and minutes components
    const timeComponents = time.split(':');
    const hoursStr = timeComponents[0]; // Extract hours component
    const minutesStr = timeComponents[1]; // Extract minutes component

    // Ask the user for the specific minutes value
    const specificMinutes = parseInt(prompt("Enter the specific minutes value:"));

    // Update the minutes component of the time
    const newTime = hoursStr + ':' + specificMinutes.toString().padStart(2, '0');

    return newTime;
}

// Example usage:
const givenTime = '10:30'; // Assuming the given time is in the format 'HH:MM'
const newTime = changeMinutesToSpecificValue(givenTime);
console.log("New time:", newTime);
Chapter 31 - 34: Question 13

Q13. Write a JavaScript function to add a specific number of hours to a given time.

Answer 13:

function addHoursToTime(time, hoursToAdd) {
    // Split the time string into hours and minutes components
    const [hoursStr, minutesStr] = time.split(':');

    // Convert the components to numbers
    let hours = parseInt(hoursStr);
    let minutes = parseInt(minutesStr);

    // Add the specified number of hours
    hours += hoursToAdd;

    // Handle cases where hours exceed 24
    if (hours >= 24) {
        hours %= 24; // Rolls over to the next day
    }

    // Format the updated time string
    const updatedHoursStr = hours.toString().padStart(2, '0');
    const updatedTime = updatedHoursStr + ':' + minutes;

    return updatedTime;
}

// Example usage:
const initialTime = '08:30'; // Given time
const hoursToAdd = 3; // Number of hours to add
const updatedTime = addHoursToTime(initialTime, hoursToAdd);
console.log("Updated time:", updatedTime);
Chapter 31 - 34: Question 14

Q14. You have to create a age calculator in JavaScript.

Answer 14:

function calculateAge(birthDateString) {    
    var currentDate = new Date();
    var birthDate = new Date(birthDateString);

    var yearsDifference = currentDate.getFullYear() - birthDate.getFullYear();
    var monthsDifference = currentDate.getMonth() - birthDate.getMonth();
    var daysDifference = currentDate.getDate() - birthDate.getDate();

    // Adjust months and years if daysDifference is negative
    if (daysDifference < 0) {
        monthsDifference--;
        var lastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 0);
        daysDifference = lastMonth.getDate() + daysDifference; // Add days of last month to the negative value
    }

    // Adjust months and years if monthsDifference is negative
    if (monthsDifference < 0) {
        yearsDifference--;
        monthsDifference = 12 + monthsDifference; // Add 12 to the negative value to get positive months difference
    }

    console.log("Years:", yearsDifference, "Months:", monthsDifference, "Days:", daysDifference);
}

// Example usage
calculateAge("1990-05-15"); // Output depends on the current date

Chapter 35 - 37: Functions

Chapter 35 - 37: Question 1

Q1. Code the first line of a function displayAlert.

Answer 1:

function displayAlert() {}
Chapter 35 - 37: Question 2

Q2. Code a function named askName that prompts the user to "Enter name" and assigns the answer to userName, which hasn't been declared beforehand.

Answer 2:

function askName() {
    var userName = prompt("Enter name");
    return userName;
}
Chapter 35 - 37: Question 3

Q3. Code a function that calls 2 other functions.

Answer 3:

function callTwoFunctions() {
    function1();
    function2();
}
Chapter 35 - 37: Question 5

Q5. Code a function that displays a prompt, "Enter name" and then displays the name in an alert. Call the function.

Answer 5:

function displayName() {
    var name = prompt("Enter name");
    alert("Assalam-U-Alaikum, " + name + "!");
}

// Calling the function
displayName();
Chapter 35 - 37: Question 6

Q6. Code a function that has 2 parameters. Concatenate them and assign the result to a variable that hasn't been declared beforehand.

Answer 6:

function concatenateStrings(string1, string2) {
    var concatenatedResult = string1 + string2;
    return concatenatedResult;
}

// Example usage
var result = concatenateStrings("Hello", "World");
console.log(result); // Output: HelloWorld
Chapter 35 - 37: Question 7

Q7. Code a function that has three parameters. Multiply them and assign them to a variable that hasn't been declared yet.

Answer 7:

function multiplyNumbers(num1, num2, num3) {
    var multipliedResult = num1 * num2 * num3;
    return multipliedResult;
}

// Example usage
var result = multiplyNumbers(2, 3, 4);
console.log(result); // Output: 24
Chapter 35 - 37: Question 8

Q8. Write a JavaScript function that takes an array of numbers as input and returns the average of those numbers.

Answer 8:

function calculateAverage(numbers) {
    // Checks if the array is empty
    if (numbers.length === 0) {
        return 0; // Return 0 if the array is empty to avoid division by zero
    }

    // Calculate the sum of all numbers in the array
    var sum = numbers.reduce(function (value1, value2) {
        return value1 + value2;
    }, 0);

    // Calculate the average by dividing the sum by the number of elements in the array
    var average = sum / numbers.length;
    
    return average;
}

// Example usage
var numbers = [10, 20, 30, 40, 50];
var average = calculateAverage(numbers);
console.log("Average:", average); // Output: Average: 30
Chapter 35 - 37: Question 9

Q9. Write a JavaScript function that takes two parameters and returns their sum.

Answer 9:

function sum(a, b) {
    return a + b;
}

// Example usage:
const result = sum(3, 4);
console.log(result); // Output: 7
Chapter 35 - 37: Question 10

Q10. Write a JavaScript function that takes an array of numbers as input and returns the average of those numbers.

Answer 10:

function calculateAverage(numbers) {
    // Check if the array is empty
    if (numbers.length === 0) {
        return 0; // Return 0 if the array is empty to avoid division by zero
    }

    // Calculate the sum of all numbers in the array using reduce method
    const sum = numbers.reduce(function (value1, value2) {
        return value1 + value2;
    }, 0);

    // Calculate the average by dividing the sum by the number of elements in the array
    const average = sum / numbers.length;
    
    return average; // Return the average
}

// Example usage:
const numbers = [1, 2, 3, 4, 5];
const average = calculateAverage(numbers);
console.log(average); // Output: 3
Chapter 35 - 37: Question 11

Q11. You have to capture the returned value from a function and store it in a variable?

Answer 11:

// Define a function that returns a value
function multiply(a, b) {
    return a * b;
}

// Call the function and capture the returned value in a variable
const result = multiply(5, 10);

// Now the variable "result" holds the returned value
console.log(result); // Output: 50
Chapter 35 - 37: Question 12

Q12. Write a function which tells letter counts of (word).

Answer 12:

function letterCounts(word) {
    var wordLength = word.length;
    return wordLength;
}

// Example usage:
let word = "Hello World";
console.log(letterCounts(word)); // Output: 11
Chapter 35 - 37: Question 13

Q13. Write a function to set (year) in date object.

Answer 13:

function setYear(date, year) {
    date.setFullYear(year);
    return date;
}

// Example usage:
let myDate = new Date();
console.log("Before setting year:", myDate);
setYear(myDate, 2020);
console.log("After setting year:", myDate);
Chapter 35 - 37: Question 14

Q14. Write a function which tells the age of a person who Born on (dateOfBirth)

Answer 14:

function calculateAge(dateOfBirth) {
    var currentDate = new Date();
    var birthDate = new Date(dateOfBirth);

    var yearsDifference = currentDate.getFullYear() - birthDate.getFullYear();
    var monthsDifference = currentDate.getMonth() - birthDate.getMonth();
    var daysDifference = currentDate.getDate() - birthDate.getDate();

    // Adjust months and years if daysDifference is negative
    if (daysDifference < 0) {
        monthsDifference--;
        var lastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 0);
        daysDifference = lastMonth.getDate() + daysDifference; // Add days of last month to the negative value
    }

    // Adjust months and years if monthsDifference is negative
    if (monthsDifference < 0) {
        yearsDifference--;
        monthsDifference = 12 + monthsDifference; // Add 12 to the negative value to get positive months difference
    }

    console.log("Years:", yearsDifference, "Months:", monthsDifference, "Days:", daysDifference);
}

// Example usage
calculateAge("2000-01-20"); // Output depends on the current date
Chapter 35 - 37: Question 15

Q15. Write a function which tells the presense of (word) in an array = ['zaid','haris','raza','abubakar','hassan','hussain','fatima'] result should be in true or false

Answer 15:

// Method using Array.includes()
function checkWordPresence(word) {
    var namesArray = ['zaid','haris','raza','abubakar','hassan','hussain','fatima'];
    return namesArray.includes(word);
}

// Method using a loop
function checkWordPresenceLoop(word) {
    var namesArray = ['zaid','haris','raza','abubakar','hassan','hussain','fatima'];
    for (var i = 0; i < namesArray.length; i++) {
        if (namesArray[i] === word) {
            return true;
        }
    }
    return false;
}

// Example usage
console.log(checkWordPresence('raza')); // Output: true
console.log(checkWordPresence('ali'));  // Output: false

console.log(checkWordPresenceLoop('raza')); // Output: true
console.log(checkWordPresenceLoop('ali'));  // Output: false
Chapter 35 - 37: Question 16

Q16. Write a function which repeat (letter) 10 times. Hint: "abcde" str.repeat(10)

Answer 16:

function repeatLetter(letter) {
    return letter.repeat(10);
}

// Example usage
console.log(repeatLetter('a')); // Output: 'aaaaaaaaaa'
console.log(repeatLetter('b')); // Output: 'bbbbbbbbbb'
Chapter 35 - 37: Question 17

Q17. write a function which reverse array = ['a','b','c','d','e'] Hint: arr.reverse()

Answer 17:

function reverseArray(arr) {
    return arr.reverse();
}

// Example usage
var arr = ['a', 'b', 'c', 'd', 'e']
console.log(reverseArray(arr)); // Output: ['e', 'd', 'c', 'b', 'a']
Chapter 35 - 37: Question 18

Q18. write a function which reverse array = ['a','b','c','d','e'] Hint: arr.reverse()

Answer 18:

function reverseNumber(num) {
    const reversedNum = parseFloat(num.toString().split('').reverse().join(''));
    return reversedNum;
}

// Example usage
const x = 32243;
console.log(reverseNumber(x)); // Output: 34223
Chapter 35 - 37: Question 19

Q19. Write a JavaScript function that checks whether a passed string is a palindrome or not? Hint: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or Wow.

Answer 19:

function checkPalindrome(str) {
    var result = str.toLowerCase().split('').reverse().join('');
    if (str.toLowerCase() == result) {
        return str + ' is a Palindrom word';
    } else {
        return str + ' is not a Palindrom word';
    }
}

// Example usage
const x = "madam";
console.log(checkPalindrome(x));
console.log(checkPalindrome("Hello"));
Chapter 35 - 37: Question 20

Q20. Write a JavaScript function that accepts a string as a parameter and converts the first letter of each word into upper case. Example string : 'the quick brown fox' Expected Output : 'The Quick Brown Fox '

Answer 20:

function capitalizeFirstLetter(str) {
    var words = str.split(' ');

    for (var i = 0; i < words.length; i++) {
        // Capitalize the first letter of each word
        words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
    }

    return words.join(' ');
}

// Example usage
var inputString = 'the quick brown fox';
var outputString = capitalizeFirstLetter(inputString);
console.log(outputString); // Output: 'The Quick Brown Fox'
Chapter 35 - 37: Question 21

Q21. Write a JavaScript function that takes an array of numbers and finds the lowest and greatest numbers, respectively. Sample array : [1,2,3,4,5] Expected Output : 1,5

Answer 21:

function findMinMax(numbers) {
    // Find the lowest and greatest numbers using Math.min and Math.max
    var lowest = Math.min(...numbers);
    var greatest = Math.max(...numbers);
    
    // Return the lowest and greatest numbers as a string
    return `${lowest},${greatest}`;
}

// Example usage
var numbersArray = [1, 2, 3, 4, 5];
var result = findMinMax(numbersArray);
console.log(result); // Output: 1,5

Chapter 38: Local vs Global Variables

Chapter 38: Question 1

Q1. Write a JavaScript function that demonstrates the usage of a local variable.

Answer 1:

function greet() {
    // This is a local variable
    var message = "Assalam-U-Alaikum!";
    console.log(message);
}

// When you call the function
greet(); // Output: Assalam-U-Alaikum!

// If you try to access the message variable outside the function, it won't work
console.log(message); // Error: message is not defined
Chapter 38: Question 2

Q2. Write a JavaScript function that demonstrates the usage of a local variable.

Answer 2:

var globalVar = "I'm a global variable";

// Function that accesses the global variable
function accessGlobal() {
    console.log(globalVar);
}

// Calling the function
accessGlobal(); // Output: I'm a global variable

Chapter 39 - 40: Switch Statements

Chapter 39: Question 1

Q1. Write a JavaScript switch statement that checks the value of a variable and performs different actions based on different cases.

Answer 1:

// Defining a variable
var color = "red";

// Switch statement to perform different actions based on the value of the variable
switch (color) {
    case "red":
        console.log("The color is red.");
        break;
    case "blue":
        console.log("The color is blue.");
        break;
    case "green":
        console.log("The color is green.");
        break;
    default:
        console.log("The color is not red, blue, or green.");
}
Chapter 39: Question 2

Q2. Write a JavaScript switch statement that check whether cityName given by user check the cityName if match alert the user and break the statement, if not default message will be shown to user.

Answer 2:

// Assuming the user's cityName is stored in a variable called userCityName
var userCityName = prompt("Enter your city name:");

// Variable containing cityName for comparison
var cityName = "New York";

// Switch statement to check if userCityName matches cityName
switch (userCityName) {
    case cityName:
        alert("Your city matches the predefined city!");
        break;
    default:
        alert("Your city didn't match the predefined city.");
}