JavaScript MCQs – Introduction to JavaScript

21.) What is the output of the following code?

console.log(1 + "2" + 3);
A) “123”
B) 6
C) 33
D) “6”

Answer: Option A

Explanation: The + operator concatenates strings when at least one operand is a string. The result is “123” because “2” is a string.

22.) 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 stands for “Not a Number,” it is considered a special numeric value in JavaScript, so typeof NaN returns “number”.

23.) What is the difference between == and === in JavaScript?

A) == checks value only, === checks both value and type.
B) === checks value only, == checks both value and type.
C) Both compare only values.
D) Both compare only types.

Answer: Option A

Explanation: == performs type coercion and compares values after converting them to a common type, while === checks both value and type strictly.

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

let x = {};
let y = {};
console.log(x == y, x === y);
A) true, true
B) false, false
C) true, false
D) false, true

Answer: Option B

Explanation: In JavaScript, objects are compared by reference, not value. Since x and y are different objects, both == and === return false.

25.) What will the following code output?

(function() {
  var a = b = 5;
})();
console.log(typeof a, typeof b);
A) “undefined”, “undefined”
B) “undefined”, “number”
C) “number”, “number”
D) “undefined”, “object”

Answer: Option B

Explanation: In the code, b is implicitly created as a global variable. a is local to the function. Outside the function, a is undefined, while b is number.

26.) Which of the following statements is true about the ‘this’ keyword in JavaScript?

A) It always refers to the global object.
B) It refers to the object that owns the function being executed.
C) It refers to the parent object of the current function.
D) It refers to the prototype of the current object.

Answer: Option B

Explanation: The value of this depends on the context in which the function is called. In most cases, it refers to the object that owns the function.

27.) What will the following code output?

let obj = {
  a: 10,
  b: function() {
    return this.a + 20;
  }
};
let fn = obj.b;
console.log(fn(), obj.b());
A) 30, 30
B) NaN, 30
C) 30, NaN
D) NaN, NaN

Answer: Option B

Explanation: When fn() is called, this is not bound to obj (default binding refers to undefined in strict mode or global object otherwise), so this.a is undefined. When obj.b() is called, this refers to obj, and this.a is 10.

Leave a Reply

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