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 ↓


Explore the index below to navigate to specific topics:

  1. Chapter 1 (Alerts)
  2. Chapter 2 (Variables for string)
  3. Chapter 3 (Variables for numbers)
  4. Chapter 4 (Variable names Legal and Illegal)
  5. Chapter 5 (Math Expression I)
  6. Chapter 6 (Math Expression II)
  7. Chapter 7 (Math Expression III)
  8. Chapter 8 (Concatenating Text Strings)
  9. Chapter 9 (Prompts)
  10. Chapter 10 (if statments)
  11. Chapter 11 (Comparison Operators)
  12. Chapter 12 (if…else and else if statements)
  13. Chapter 13 (Testing sets of conditions)
  14. Chapter 14 (If statements nested)
  15. Chapter 15 (Array I)
  16. Chapter 16 (Array II)
  17. Chapter 17 (Array III)
  18. Chapter 18 - 20 (for Loops)

Chapter 1: Alerts

Chapter 1: Question 1

Q1. Alert these following (individually):

  • First Name
  • Last Name
  • Email
  • Phone Number
  • Password

Answer 1:

alert("First Name");
alert("Last Name");
alert("Email");
alert("Phone Number");
alert("Password");
Chapter 1: Question 2

Q2. Correct this statement: alert"You're learning JavaScript!";

Answer 2:

alert("You're learning JavaScript!");
Chapter 1: Question 3

Q3. Code an alert statement displaying any message you like.

Answer 3:

alert("Hello! Welcome to JavaScript World!");

Chapter 2: Variables for string

Chapter 2: Question 1

Q1. Declare any variable in the camelCase format.

Answer 1:

let myVariableName = "example";
Chapter 2: Question 2

Q2. Declare a variable of your choice without defining it. Then, in a second statement, assign it a string of your choice.

Answer 2:

let myVariable; // Declaring a variable without defining it
myVariable = "Hello, world!"; // Assigning a string to the variable in a separate statement
Chapter 2: Question 3

Q3. Declare the variable teamName and Alert your Team name.

Answer 3:

let teamName = "Champions"; // Declaring the variable teamName and assigning a team name
alert(teamName); // Displaying the team name using the alert function
Chapter 2: Question 4

Q4. This statement has already been coded. var bestMan = "Charlie"; Assign the variable a new string.

Answer 4:

var bestMan = "Charlie"; // This statement has already been coded
bestMan = "David"; // Assigning a new string to the variable bestMan

Chapter 3: Variables for numbers

Chapter 3: Question 1

Q1. Declare a variable “caseQty”

Answer 1:

let caseQty; // Declaration of the variable caseQty
Chapter 3: Question 2

Q2. Assign to the variable caseQty, which has already been declared, the value 144.

Answer 2:

let caseQty; // Declaration of the variable caseQty
caseQty = 144; // Assigning the value 144 to the variable caseQty
Chapter 3: Question 3

Q3. Rewrite this statement so the variable can be used in a math operation. var num = "9";

Answer 3:

var num = "9"; // Original statement with num as a string
var num = parseInt("9"); // Using parseInt to convert the string "9" to the number 9
Chapter 3: Question 4

Q4. In one statement declare a variable. In a second statement assign it the sum of 2 numbers.

Answer 4:

let result; // Declaring a variable named result
result = 5 + 7; // Assigning the sum of 5 and 7 to the variable result
Chapter 3: Question 5

Q5. What is the value of orderTotal? var merchTotal = 100; var shippingCharge = 10; var orderTotal = merchTotal + shippingCharge;

Answer 5:

var merchTotal = 100;
var shippingCharge = 10;
var orderTotal = merchTotal + shippingCharge;

// The value of orderTotal is the sum of merchTotal and shippingCharge
// orderTotal = merchTotal + shippingCharge
// orderTotal = 100 + 10
// orderTotal = 110
Chapter 3: Question 6

Q6. In the first statement declare a variable and assign it a number. In the second statement, change the value of the variable by adding it together with a number.

Answer 6:

let num = 5; // Declaring a variable num and assigning it a number, for instance, 5
num += 3; // This is shorthand for num = num + 3;

Chapter 4: Variable names Legal and Illegal

Chapter 4: Question 1

Q1. Correct this statement. var product cost = 3.45;

Answer 1:

var productCost = 3.45;
// By removing the space and combining 'product' and 'cost' into a single variable name ('productCost'), the statement becomes valid in JavaScript.
Chapter 4: Question 2

Q2. Rewrite this using camelCase. var Nameofband;

Answer 2:

var nameOfBand;
Chapter 4: Question 3

Q3. In a single statement declare a legally-named variable and assign a number to it.

Answer 3:

let myNumber = 25; // Declaring a variable named myNumber and assigning the number 25 to it
Chapter 4: Question 4

Q4. Declare a variable that is a combination of your first and last names. Use camelCase.

Answer 4:

let johnDoe = "JohnDoe";
Chapter 4: Question 5

Q5. List the legal and Illegal Variables.

Answer 5:

Legal Variables:
    • A variable name must start with a letter, underscore (_), or dollar sign ($). eg: firstName , _myVariable , $amount
    • Subsequent characters can be letters, numbers, underscores, or dollar signs. eg: my_variable , another123
    • Variable names are case-sensitive. eg: myVariable , myvariable | Each name represents a unique variable due to the case sensitivity.

Illegal Variables:
    • Cannot start with a number. eg: 123variable
    • Cannot contain spaces or special characters (except underscore or dollar sign). eg: my variable (contains a space) , my-variable (contains a hyphen) , !illegal (contains a special character)

Chapter 5: Math Expression I

Chapter 5: Question 1

Q1. What is the name and symbol of the arithmetic operator that gives you the remainder when one number is divided by another?

Answer 1:

// The arithmetic operator that gives you the remainder when one number is divided by another is called the "modulo" operator.
// The symbol for the modulo operator is the percent sign (%).
// For example:
7 % 3 // would give a result of 1 because 7 divided by 3 gives a quotient of 2 with a remainder of 1.
Chapter 5: Question 2

Q2. What is the value of num? var num = 20 % 6;

Answer 2:

var num = 20 % 6; // The value of num is 2 (remainder of 20 divided by 6)
Chapter 5: Question 3

Q3. In a single statement, declare the variable largeNum and assign it the result of 1,000 multiplied by 2,000.

Answer 3:

let largeNum = 1000 * 2000;
Chapter 5: Question 4

Q4. Assign to a variable the value represented by one variable subtracted from the value represented by another variable.

Answer 4:

var value1 = 20;
var value2 = 8;
var result = value1 - value2;

console.log(result); // Expected output: 12 because 20 - 8 = 12
Chapter 5: Question 5

Q5. Assign to a variable the remainder when one number is divided by another. The variable hasn't been declared beforehand. Make up the variable name.

Answer 5:

var myRemainder = 15 % 7;
console.log(myRemainder); // Expected output: 1
Chapter 5: Question 6

Q6. Code an alert that displays the result of a multiplication on 2 numbers.

Answer 6:

var num1 = 5;
var num2 = 8;
var result = num1 * num2;

alert("The result of multiplying " + num1 + " and " + num2 + " is: " + result);
// Displaying the result using an alert function

Chapter 6: Math Expression II

Chapter 6: Question 1

Q1. Code a short form of x = x + 1; Use either of the two legal expressions.

Answer 1:

var x = 5;
x += 1; // This is a shorter form of x = x + 1;
console.log(x); // Output will be 6
Chapter 6: Question 2

Q2. If x has a value of 100, what is the fastest way to reduce it to 99 with a math expression?

Answer 2:

var x = 100;
x--; // This will decrement the value of x by 1
console.log(x); // Output will be 99
Chapter 6: Question 3

Q3. var x = 50; var y = x++; What is the value of y?

Answer 3:

var x = 50; // Assigns the value 50 to variable x
var y = x++; // Assigns the current value of x to y and then increments x by 1

// Displaying the values of x and y
console.log("Value of y: " + y); // Output: Value of y: 50
console.log("Value of x: " + x); // Output: Value of x: 51

// Explanation of the assignment and increment operation
// y now holds the initial value of x before the increment
// x is incremented after assigning its value to y
Chapter 6: Question 4

Q4. var y = 50; var z = --y; What is the value of z?

Answer 4:

var y = 50; // Assigns the value 50 to variable y
var z = --y; // Decrements y by 1 and assigns the decremented value to z

// Displaying the values of y and z
console.log("Value of z: " + z); // Output: Value of z: 49
console.log("Value of y: " + y); // Output: Value of y: 49 (as y was decremented by 1)

// Explanation of the decrement operation
// --y decrements the value of y before assigning it to z
Chapter 6: Question 5

Q5. In a single statement, decrement num and assign its original value to newNum.

Answer 5:

var num = 10;
var newNum = num--;

console.log("Value of newNum: " + newNum); // Output: Value of newNum: 10 (as num's original value is assigned to newNum)
console.log("Value of num: " + num); // Output: Value of num: 9 (as num was decremented by 1)

// Explanation:
// In a single statement, newNum is assigned the value of num, and immediately after, num is decremented by 1 using the '--' operator.
Chapter 6: Question 6

Q6. In a single statement add 1 to a variable and assign its original value to another variable.

Answer 6:

var originalVar = 10; // Example value for the original variable
var newVar = originalVar++; // Increment originalVar by 1 and assign its original value to newVar

console.log("Value of newVar: " + newVar); // Output: Value of newVar: 10 (as originalVar's original value is assigned to newVar)
console.log("Value of originalVar: " + originalVar); // Output: Value of originalVar: 11 (as originalVar was incremented by 1)
Chapter 6: Question 7

Q7. Assign a number value to a variable. Increment the variable. Display the new value in an alert

Answer 7:

let numberValue = 5; // Assigning a number value to the variable
numberValue++; // Incrementing the variable by 1

alert(numberValue); // Displaying the new value in an alert

Chapter 7: Math Expression III

Chapter 7: Question 1

Q1. var calculatedNum = 2 + (2 * 6); What is the value of calculatedNum?

Answer 1:

var calculatedNum = 2 + (2 * 6); // Calculation
console.log(calculatedNum); // Output: 14

// Explanation:
// 2 + (2 * 6)
// 2 * 6 = 12
// 2 + 12
// 2 + 12 = 14
Chapter 7: Question 2

Q2. var calculatedNum = (2 + 2) * 6; What is the value of calculatedNum?

Answer 2:

var calculatedNum = (2 + 2) * 6; // Calculation
console.log(calculatedNum); // Output: 24

// Explanation:
// (2 + 2) * 6
// 2 + 2 = 4
// 4 * 6
// 4 * 6 = 24
Chapter 7: Question 3

Q3. var calculatedNum = (2 + 2) * (4 + 2); What is the value of calculatedNum?

Answer 3:

var calculatedNum = (2 + 2) * (4 + 2); // Calculation
console.log(calculatedNum); // Output: 24

// Explanation:
// (2 + 2) * (4 + 2)
// 2 + 2 = 4
// 4 + 2 = 6
// (2 + 2) * (4 + 2) becomes 4 * 6
// 4 * 6 = 24
Chapter 7: Question 4

Q4. var calculatedNum = ((2 + 2) * 4) + 2; What is the value of calculatedNum?

Answer 4:

var calculatedNum = ((2 + 2) * 4) + 2; // Calculation
console.log(calculatedNum); // Output: 18

// Explanation:
// ((2 + 2) * 4) + 2
// 2 + 2 = 4
// 4 * 4 = 16
// 16 + 2 = 18
Chapter 7: Question 5

Q5. Write a statement that assigns to cost the result of 2 + 2 * 4 + 10, clarified with parentheses, producing 56.

Answer 5:

2 + 2 * 4 + 10 // Original expression

// To get 56, we need to rearrange it using parentheses:
(2 + 2) * (4 + 10) // Rearranged expression

// Now, solve this expression to verify if it results in 56:
(2 + 2) * (4 + 10)
= 4 * 14
= 56

var cost = (2 + 2) * (4 + 10);
console.log(cost); // Output: 56
Chapter 7: Question 6

Q6. Write a statement that assigns to units the result of 2 + 2 * 4 + 10, clarified with parentheses, producing 20.

Answer 6:

2 + 2 * 4 + 10 // Original expression

// To get 20, we need to rearrange it using parentheses:
2 + (2 * 4) + 10 // Rearranged expression

// Now, solve this expression to verify if it results in 20:
2 + (2 * 4) + 10
= 2 + 8 + 10
= 20

var units = 2 + (2 * 4) + 10;
console.log(units); // Output: 20
Chapter 7: Question 7

Q7. Write a statement that assigns to pressure the result of 4 / 2 * 4, clarified with parentheses, producing 5.

Answer 7:

4 / 2 * 4 // Original expression

// To get 0.5, we need to rearrange it using parentheses:
4 / (2 * 4) // Rearranged expression

// Now, solve this expression to verify if it results in 0.5:
4 / (2 * 4)
= 2 * 4 = 8
= 4 / 8 = 0.5
= 0.5

// Note: The rearranged expression results in 0.5, not 5.
// Given the structure of the expression, it's not possible to attain the result of 5 using parentheses without altering the expression further.

var pressure = 4 / (2 * 4);
console.log(pressure); // Output: 0.5

Chapter 8: Concatenating Text Strings

Chapter 8: Question 1

Q1. var num = "2" + "2"; What is the value of num? Include quotation marks.

Answer 1:

var num = "2" + "2";
console.log(num); // Output: 22

// Explanation:
// "2" + "2" = 22 Because the first value is string ('2') and another value is also a string ('2'). So when we try to add a string into another string, JavaScript concatenates the strings instead of adding them.
Chapter 8: Question 2

Q2. message = ("Hello," + "Dolly"); What is the value of message? (Include the quotation marks.) Alert the statement

Answer 2:

let message = ("Hello," + "Dolly");
                        alert(message); // Output: Hello,Dolly
Chapter 8: Question 3

Q3. alert("33" + 3); What message displays in the alert box?

Answer 3:

console.log("33" + 3); // Output: 333

// Explanation:
// "33" + 3 = 333 Because the first value is a string ('33') and another value is a number (3). So when we try to add a string into a number, JavaScript concatenates it instead of adding them.
Chapter 8: Question 4

Q4. Write an alert that displays the concatenation of the two parts of "Pakistan Zindabad".

Answer 4:

// Declaring variables for the two parts of the phrase
var firstPart = "Pakistan";
var secondPart = "Zindabad";

alert(`${firstPart} ${secondPart}`); // Using template literals to concatenate the two parts with a space in between
Chapter 8: Question 5

Q5. Write a statement that assigns to a variable the concatenation of a string with a number.

Answer 5:

var concatenatedString; // Declaring a variable
concatenatedString = "Hello " + 123; // Concatenating a string and a number and assigning it to the variable
console.log(concatenatedString); // Output: Hello 123
Chapter 8: Question 6

Q6. Assign strings to two variables. Then concatenate them and assign the result to a third variable.

Answer 6:

// Declaring two variables with strings
var firstString = "Hello, ";
var secondString = "world!";

// Concatenating the strings and assigning the result to a third variable
var concatenatedString = firstString + secondString;

console.log(concatenatedString); // Output: Hello, world!

Chapter 9: Prompts

Chapter 9: Question 1

Q1. Code a prompt with the message "Enter first name". The user's response is assigned to firstName.

Answer 1:

let firstName = prompt("Enter first name");
Chapter 9: Question 2

Q2. Code a prompt with the message "Country?" and the default answer "China". The user's response is assigned to country.

Answer 2:

let country = prompt("Country?", "China");
Chapter 9: Question 3

Q3. Correct this statement var yourName = prompt(Enter Your Name");

Answer 3:

var yourName = prompt(Enter Your Name"); // Incorrect statement

var yourName = prompt("Enter Your Name"); // Corrected statement
// This fixed the missing opening double quote at the beginning of the prompt message.
Chapter 9: Question 4

Q4. Code a prompt that specifies a string as the message Include a default input.

Answer 4:

var userInput = prompt("Enter your answer:", "Default Value");
Chapter 9: Question 5

Q5. Assign strings to two variables. Code a prompt specifying the first variable as the message and the second variable as the default response. Assign the user's response to a third variable.

Answer 5:

var message = "Enter your answer:"; // Contains the message to display in the prompt.
var defaultResponse = "Default Value"; // Contains the default value displayed in the prompt.

var userInput = prompt(message, defaultResponse); // Will hold the user's response from the prompt.
Chapter 9: Question 6

Q6. Display a prompt, including both a message and a default response. Display the user's response in an alert.

Answer 6:

let userInput = prompt("Enter your answer", "Albert Einstein")
alert;("Your answer is: " + userInput);

Chapter 10: if statments

Chapter 10: Question 1

Q1. var city = "Karachi" if (city = "Karachi") { console.log("The City OF Lights") Correct the above statement: Also try this statement by yourself

Answer 1:

// Given Code
var city = "Karachi";

// Mistake 1: Using assignment operator (=) instead of comparison operator (===).
if (city = "Karachi") {
    console.log("The City OF Lights");
// Mistake 2: Missing closing curly brace for the 'if' statement.


// Corrected Code 
var city = "Karachi";

// Corrected: Using strict equality comparison operator (===).
if (city === "Karachi") {
    console.log("The City OF Lights");
} // Corrected: Added the missing closing curly brace for the 'if' statement.
Chapter 10: Question 2

Q2. This is the first line of an if statement: if (x === y) { Complete the statement. If the condition is true, display a box that asks the user value of z? and assign it to another variable.

Answer 2:

if (x === y) {
    var z = prompt("Enter the value of z?");
    var anotherVariable = z;
}
Chapter 10: Question 3

Q3. Code an if statement that tests if ZipCode is "10010" so, Alert that "Karachi". if not then alert ("Please write correct city")

Answer 3:

if (ZipCode == "10010") {
    alert("Karachi");
} else {
    alert("Please write correct city");
}
Chapter 10: Question 4

Q4. Code an if statement. Test whether a variable has a particular numerical value. If so, assign a new value to that variable, as in x = 1;

Answer 4:

// Assuming x is the variable we want to test and potentially change
let x = 5; // Initial value of x

if (x === 5) { // Checking if x is equal to 5
    x = 10; // Assigning a new value to x if the condition is true
}

Chapter 11: Comparison Operators

Chapter 11: Question 1

Q1. Code the first line of an if statement that tests whether one variable is unequal to another. (Use !)

Answer 1:

if (x !== y) {
    // Code to execute if x is not equal to y
}
Chapter 11: Question 2

Q2. Code the first line of an if statement that tests whether the value represented by a variable is greater than or equal to the value represented by another variable.

Answer 2:

if (num1 >= num2) {
    // Code to execute if num1 is greater than or equal to num2
}
Chapter 11: Question 3

Q3. Code an if statement. Test whether a variable is unequal to a particular number. If so, assign a number to that variable.

Answer 3:

var x = 10;
var specificNumber = 5;

if (x !== specificNumber) {
    x = specificNumber; // Reassigning x if it's not equal to specificNumber
}
Chapter 11: Question 4

Q4. Code an if statement that tests whether a number is unequal to a different number. If the condition is true (it will be), display a congratulations alert.

Answer 4:

let numberOne = 10;
let numberTwo = 5;

if (numberOne !== numberTwo) {
    alert("Congratulations!");
}
Chapter 11: Question 5

Q5. Code a prompt asking for your first name. Code an if statement that tests whether the name you entered is unequal to another name. If the condition is true (it will be), display an alert that says "No match"

Answer 5:

const userName = prompt("Enter your first name");
const comparisonName = "John";

if (userName !== comparisonName) {
    alert("No match");
}

Chapter 12: if…else and else if statements

Chapter 12: Question 1

Q1. Code an if statement that tests whether the value represented by a variable is greater than or equal to the value represented by another variable. If so, display an alert. If not, display a different alert.

Answer 1:

const variable1 = 10;
const variable2 = 5;

if (variable1 >= variable2) {
    alert("Variable1 is greater than or equal to Variable2");
} else {
    alert("Variable1 is less than Variable2");
}
Chapter 12: Question 2

Q2. Write a program using if else and else if statement which take marks from user. And the program will calculate your percentage and give you grade A/C to Your percentage. (MARKSHEET)

Answer 2:

let marksEng = parseInt(prompt("Enter English marks (out of 100)", "0"));
while (marksEng > 100 || isNaN(marksEng)) {
    alert("Enter Valid English Marks");
    marksEng = parseInt(prompt("Enter English marks (out of 100)", "0"));
}

let marksMaths = parseInt(prompt("Enter Maths marks (out of 100)", "0"));
while (marksMaths > 100 || isNaN(marksMaths)) {
    alert("Enter Valid Mathematics Marks");
    marksMaths = parseInt(prompt("Enter Maths marks (out of 100)", "0"));
}

let marksUrdu = parseInt(prompt("Enter Urdu marks (out of 100)", "0"));
while (marksUrdu > 100 || isNaN(marksUrdu)) {
    alert("Enter Valid Urdu Marks");
    marksUrdu = parseInt(prompt("Enter Urdu marks (out of 100)", "0"));
}

let marksScience = parseInt(prompt("Enter Science marks (out of 100)", "0"));
while (marksScience > 100 || isNaN(marksScience)) {
    alert("Enter Valid Science Marks");
    marksScience = parseInt(prompt("Enter Science marks (out of 100)", "0"));
}

let marksComputer = parseInt(prompt("Enter Computer marks (out of 100)", "0"));
while (marksComputer > 100 || isNaN(marksComputer)) {
    alert("Enter Valid Urdu Marks");
    marksComputer = parseInt(prompt("Enter Computer marks (out of 100)", "0"));
}

let totalMarks = 500;
let gainedMarks = marksEng + marksMaths + marksUrdu + marksScience + marksComputer;
let percentage = gainedMarks * 100 / totalMarks;

alert("Your Total Percentage is: " + percentage.toFixed(1) + "%");

if (gainedMarks >= 490) {
    alert("Grade: A+");
} else if (gainedMarks >= 400) {
    alert("Grade: A");
} else if (gainedMarks >= 350) {
    alert("Grade: B");
} else if (gainedMarks >= 250) {
    alert("Grade: C");
} else if (gainedMarks >= 100) {
    alert("Grade: D");
} else {
    alert("Grade: Fail");
}
Chapter 12: Question 3

Q3. Write a program using if else and else if statement which take marks from user. And the program will calculate your percentage and give you grade A/C to Your percentage. (MARKSHEET)

Answer 3:

if (a === 10) {
    alert("a is 10");
} else {
    alert("The correct value of a is 10");
}
Chapter 12: Question 4

Q4. Prompt the user to enter a city. If the city is Karachi, display an alert acknowledging it is Karachi. If not, check to see if it's Lahore. If it is, display an alert acknowledging it's Lahore. Otherwise, display a different alert.

Answer 4:

let city = prompt("Enter a city:");

if (city === "Karachi") {
    alert("It's Karachi!");
} else if (city === "Lahore") {
    alert("It's Lahore!");
} else {
    alert("Enter a different city");
}

Chapter 13: Testing sets of conditions

Chapter 13: Question 1

Q1. Code the first line of an if statement that tests whether both are true: a has the same value as b and c has the same value as d.

Answer 1:

if (a === b && c === d) {
    // Code to execute if both conditions are true
}
Chapter 13: Question 2

Q2. Code the first line of an if statement that tests whether either or both are true: a has the same value as b or c doesn't have the same value as d.

Answer 2:

if (a === b || c !== d) {
    // Code to execute if either or both conditions are true
}
Chapter 13: Question 3

Q3. Code the first line of an if statement that tests whether I. name is either "Hamza" or "Arsalan". II. age is Less than 60.

Answer 3:

if ((name === "Hamza" || name === "Arsalan") && age < 60) {
    // Code to execute if both conditions are true
}
Chapter 13: Question 4

Q4. Declare two variables and assign them number values. If the first variable is less than the second variable or greater than the second variable, display an alert.

Answer 4:

let firstVariable = 5;
let secondVariable = 10;

if (firstVariable < secondVariable || firstVariable > secondVariable) {
    alert("First variable is not equal to the second variable.");
}
Chapter 13: Question 5

Q5. Declare 2 variables. Assign one of them your first name and the other one your last name. Code 2 prompts, asking for your first and your last name. If your answers match the two variables, display an alert.

Answer 5:

let firstName = "Subaiyal";
let lastName = "Rehan";

let userFirstName = prompt("Please enter your first name:");
let userLastName = prompt("Please enter your last name:");

if (userFirstName === firstName && userLastName === lastName) {
    alert("Your name matches!");
} else {
    alert("Your name doesn't match!");
}

Chapter 14: If statements nested

Chapter 14: Question 1

Q1. Code an if statement enclosing a nested if. If password is not empty, then check if password is not greater than 5 , then display an alert that says "Password must be greater than 5" if greater than 5 then Alert "OK".

Answer 1:

let password = prompt("Please enter your password:");

if (password !== "") {
    if (password.length <= 5) {
    alert("Password must be greater than 5 characters.");
    } else {
    alert("OK");
    }
} else {
    alert("Password cannot be empty.");
}
Chapter 14: Question 2

Q2. Try this statement by yourself if (a === 1) { if (c === "Max") { alert("OK"); } }

Answer 2:

let a = 1;
let c = "Max";

if (a === 1) {
    if (c === "Max") {
    alert("OK");
    }
}

/* The provided code checks two conditions:

1. It first checks if a is equal to 1.
2. If the first condition is true, then it checks if c is equal to "Max".

If both conditions are true, it will trigger the alert saying "OK". Otherwise, nothing happens. */
Chapter 14: Question 3

Q3. Code the first line of an if statement that avoids the nesting above by testing for multiple conditions. if (a === 1) { if (c === "Max") { alert("OK"); } }

Answer 3:

// Original nested code
if (a === 1) {
    if (c === "Max") {
    alert("OK");
    }
}

// Using logical AND (&&) operator to merge conditions
if (a === 1 && c === "Max") {
    alert("OK");
}

/* Explanation:
    - The corrected code uses && to check both conditions.
    - If 'a' is 1 AND 'c' is "Max", it triggers the alert("OK").
    - The logical AND (&&) requires both conditions to be true for the alert to execute.
*/
Chapter 14: Question 4

Q4. Declare two variables and assign them the same number value. Test two conditions, using nested if statements. Test whether the first variable equals the second variable and also whether it is less than or equal to the second variable. If the test passes—and it will—display an alert message.

Answer 4:

// Declaring and assigning values to variables
let firstVar = 5;
let secondVar = 5;

// Testing conditions using nested if statements
if (firstVar === secondVar) {
    if (firstVar <= secondVar) {
    alert("Conditions passed!");
    }
}

Chapter 15: Array I

Chapter 15: Question 1

Q1. Declare an empty array.

Answer 1:

let emptyArray = [];
Chapter 15: Question 2

Q2. Code an array with 1 string element

Answer 2:

let mixedArray = ['Hello', 2, true];
Chapter 15: Question 3

Q3. var alphabet = ["h","i","j","k"]. Now print the letter “j” in alert using array index

Answer 3:

var alphabet = ["h", "i", "j", "k"];
alert(alphabet[2]); // This will display 'j' in an alert, Because JavaScript index starts from 0
Chapter 15: Question 4

Q4. var alphabet=["h","i","j","k", “l”,”m”, “n”, “o”]. Find the total length of array.

Answer 4:

let alphabet = ["h", "i", "j", "k", "l", "m", "n", "o"];
console.log(alphabet.length); // This will log the length of the array
Chapter 15: Question 5

Q5. Declare an array with one element and Add a second element with index in array. Create an alert whose message is the new element.

Answer 5:

let arr = ["First"];
arr[1] = "Two";
alert(arr[1]);

Chapter 16: Array II

Chapter 16: Question 1

Q1. Code an array with 1 string element. Add an additional element to the array using push. Create an alert whose message is the last element.

Answer 1:

let myArray = ["firstElement"]; // Declaring an array with one string element
myArray.push("secondElement"); // Adding an additional element using push

let lastElement = myArray[myArray.length - 1]; // Get the last element in the array
alert(lastElement); // Displaying the last element in an alert
Chapter 16: Question 2

Q2. var Alphabet=["h","i","j","k"] Remove the last element from the array Alphabet.

Answer 2:

let Alphabet = ["h", "i", "j", "k"];
Alphabet.pop(); // Removes the last element

console.log(Alphabet); // Displays the updated array in the console
Chapter 16: Question 3

Q3. var Alphabet=["h","i","j","k"] Add a new element, a number, to the end of an array.

Answer 3:

let Alphabet = ["h", "i", "j", "k"];
Alphabet.push(5); // Adds the number 5 to the end of the array

console.log(Alphabet); // Displays the updated array in the console

Chapter 17: Array III

Chapter 17: Question 1

Q1. var sizes = ["S", "M", "XL", "XXL", "XXXL"]. Remove the first element of an array.

Answer 1:

let sizes = ["S", "M", "XL", "XXL", "XXXL"];
sizes.shift(); // Removes the first element from the array

console.log(sizes); // Displays the updated array in the console
Chapter 17: Question 2

Q2. var sizes = ["S", "M", "XL", "XXL", "XXXL"]. Add three number elements to the beginning of an array.

Answer 2:

let sizes = ["S", "M", "XL", "XXL", "XXXL"];
sizes.unshift(1, 2, 3); // Adds three number elements to the beginning of the array

console.log(sizes); // Displays the updated array in the console
Chapter 17: Question 3

Q3. Declare an array with one element. Add a second element to the beginning of the array. Create an alert whose message is the new first element.

Answer 3:

let myArray = ["firstElement"]; // Declaring an array with one element
myArray.unshift("newFirstElement"); // Adding a second element to the beginning of the array

alert(myArray[0]); // Displaying an alert with the new first element of the array
Chapter 17: Question 4

Q4. var sizes = ["S", "M", "XL", "XXL", "XXXL"]. Insert "L" into the array between "M" and "XL".

Answer 4:

let sizes = ["S", "M", "XL", "XXL", "XXXL"]; // Given array
sizes.splice(2, 0, "L"); // Inserts "L" into the array between "M" and "XL"

console.log(sizes); // Displays the updated array in the console
Chapter 17: Question 5

Q5. var sizes = ["S", "M", "XL", "XXL", "XXXL"]. Copy the first 3 sizes of the array and put them into a new array, regSizes.

Answer 5:

var sizes = ["S", "M", "XL", "XXL", "XXXL"];
var regSizes = sizes.slice(0, 3);
Chapter 17: Question 6

Q6. var pets = ["dog", "cat", "ox", "duck", "frog"]. Add 2 elements after "dog" and remove "cat", "ox", and "duck".

Answer 6:

var pets = ["dog", "cat", "ox", "duck", "frog"];
pets.splice(1, 3, "parrot", "hamster");
console.log(pets); // Output: ["dog", "parrot", "hamster", "frog"]
Chapter 17: Question 7

Q7. var pets = ["dog", "cat", "ox", "duck", "frog"]; Remove "cat" and "ox".

Answer 7:

var pets = ["dog", "cat", "ox", "duck", "frog"];
pets.splice(1, 2); // Removes "cat" and "ox"
console.log(pets); // Output: ["dog", "duck", "frog"]
Chapter 17: Question 8

Q8. var pets = ["dog", "cat", "ox", "duck", "frog", "flea"]; Reduce it to "duck" and "frog" using slice.

Answer 8:

var pets = ["dog", "cat", "ox", "duck", "frog", "flea"];
pets = pets.slice(3, 5);
console.log(pets); // Output: ["duck", "frog"]

Chapter 18 - 20: for Loops

Chapter 18-20: Question 1

Q1. Write a statement in which loop is to run 10 times.

Answer 1:

for (let i = 0; i < 10; i++) {
    // Your code to be executed 10 times goes here
}
Chapter 18-20: Question 2

Q2. Code the first line of a for loop with the usual counter name, usual starting value, and usual increment. Run it 12 times using <= to specify how many loops.

Answer 2:

for (let i = 1; i <= 12; i++) {
    // Your code to be executed 12 times goes here
}
Chapter 18-20: Question 3

Q3. What are the 5 characters missing from this code, excluding any spaces that are missing? Type them in order, with no spaces or commas between them. for var i = 0 i <= 4 i++

Answer 3:

//Given code:
for var i = 0 i <= 4 i++

// To fix the code we need: (;;){}
// Corrected code:
for (var i = 0; i <= 4; i++) {
     
}
Chapter 18-20: Question 4

Q4. Code the first line of a for loop with a counter name that's not i. Code the usual starting value and usual increment. Run it 100 times using < to specify how many loops.

Answer 4:

for (let count = 0; count < 100; count++) {
    // Your code here
}
Chapter 18-20: Question 5

Q5. Code the first line of a for loop with the usual counter and the usual starting value. Run it 3 times using > to specify how many loops. Decrement it with each iteration.

Answer 5:

for (let i = 3; i > 0; i--) {
    // Your code here
}
Chapter 18-20: Question 6

Q6. The statement assigns the number of elements in the array to the variable.

Answer 6:

let arrayLength = array.length;
Chapter 18-20: Question 7

Q7. Set a variable named “flag” with an initial Boolean value of your choice.

Answer 7:

let flag = true; // or false, based on your choice
Chapter 18-20: Question 8

Q8. Code the first line of a for loop with the usual counter, the usual starting value, and the usual incrementing. Limit the number of loops by the number of elements in the array pets.

Answer 8:

for (let i = 0; i < pets.length; i++) {
    // Your loop code here
}
Chapter 18-20: Question 9

Q9. Set a for loop to run 10 iterations. On the second iteration, display the counter in an alert. (It should be 1.) Break out of the loop.

Answer 9:

for (let i = 0; i < 10; i++) {
    if (i === 1) {
        alert(i);
        break;
    }
}
Chapter 18-20: Question 10

Q10. Create an array which contains user names Code a prompt with the message "Enter first name". The user's response is assigned to firstName. Code the first line of a for loop with the usual counter, the usual starting value, and the usual incrementing. Limit the number of loops by the number of elements in the array user names. Code an if statement that tests the presense of (user name) in an array. If user name match Alert that "Enter". if not then alert ("Please write correct user name").

Answer 10:

const userNames = ["Abdul Basit", "Hamza", "Arsalan"]; 

let firstName = prompt("Enter first name");

for (let i = 0; i < userNames.length; i++) {
    if (firstName === userNames[i]) {
        alert("Enter");
        break;
    } else {
        alert("Please write correct user name");
        break;
    }
}
Chapter 18-20: Question 11

Q11. Complete this code to display an alert if a match isn't found. var matchFound = false; for (var i = 0; i < list.length; i++) { if (userInput===list[i]) { alert("Match found"); matchFound=true; break; } };

Answer 11:

var matchFound = false;
for (var i = 0; i < list.length; i++) {
    if (userInput === list[i]) {
    alert("Match found");
    matchFound = true;
    break;
    }
}

if (!matchFound) {
    alert("No match found");
}
Chapter 18-20: Question 12

Q12. var firstArr = [“a”, “b”, “c”, “d”, “e”, “f”]; var secondArr = [1, 2, 3, 4, 5, 6]; Code the first line of a for loop with the usual counter, the usual starting value, and the usual incrementing. Limit the number of loops by the number of elements in the array firstArr. In the scope of main loop Code the nested loop. Limit the number of nested loops by the number of elements in the array secondArr. After that concatenate the both loops. Expected Output: a1 a2 a3 a4 … f6

Answer 12:

// Declaring two arrays: one with letters and the other with numbers
var firstArr = ["a", "b", "c", "d", "e", "f"];
var secondArr = [1, 2, 3, 4, 5, 6];

// Loop through the letters array
for (let i = 0; i < firstArr.length; i++) {
    for (let j = 0; j < secondArr.length; j++) {
        // Concatenating each element of the first array with each element of the second array
        console.log(firstArr[i] + secondArr[j]);
    }
}