JavaScript MCQs – JavaScript Basics

11.) What happens when a return statement is used inside a forEach loop?

A) The loop stops.
B) It exits the function containing the loop.
C) It skips to the next iteration.
D) It throws an error.

Answer: Option B

Explanation: A return inside a forEach loop exits the entire function because forEach does not have a mechanism to terminate or continue the loop itself.

12.) Which keyword is used to stop a loop in JavaScript?

A) break
B) stop
C) exit
D) end

Answer: Option A

Explanation: The break keyword is used to terminate a loop prematurely.

13.) Which operator is used to check for inequality in JavaScript?

A) !=
B) !==
C) Both A and B
D) None of the above

Answer: Option C

Explanation: != checks value inequality, while !== checks value and type inequality.

14.) Which method is used to remove the last element from an array?

A) pop()
B) shift()
C) splice()
D) remove()

Answer: Option A

Explanation: The pop() method removes the last element from an array.

15.) What is the purpose of the splice() method?

A) To remove elements from an array.
B) To add elements to an array.
C) To remove and/or add elements to an array.
D) None of the above.

Answer: Option C

Explanation: The splice() method can be used to add, remove, or replace elements in an array.

16.) What will the following code output?

console.log(5 / 0);
A) 0
B) NaN
C) Infinity
D) undefined

Answer: Option A

Explanation: Although NaN means “Not a Number,” its type is number.

17.) What will the following code output?

let x = 10;  
let y = (x++, x + 5);  
console.log(x, y);

A) 11, 15
B) 11, 16
C) 10, 15
D) 10, 16

Answer: Option A

Explanation: The , operator evaluates each of its operands and returns the value of the last operand. Here, x++ increments x to 11, but x + 5 evaluates with the original value of x, returning 15.

18.) What is the result of the following code?

console.log(typeof NaN);

A) “number”
B) “NaN”
C) “undefined”
D) “object”

Answer: Option A

Explanation: Although NaN means “Not a Number,” its type is number.

19.) What will the following code output?

console.log(0.1 + 0.2 === 0.3);
A) true
B) false
C) undefined
D) It throws an error.

Answer: Option B

Explanation: Due to floating-point precision issues in JavaScript, 0.1 + 0.2 results in 0.30000000000000004, which is not strictly equal to 0.3

20.) What will the following code output?

let arr = [1, 2, 3];  
arr[100] = 4;  
console.log(arr.length);

A) 3
B) 4
C) 101
D) undefined

Answer: Option C

Explanation: Assigning a value at an index greater than the current length creates sparse arrays. The length property updates to reflect the highest index + 1, resulting in 101.

Leave a Reply

Your email address will not be published. Required fields are marked *