JavaScript MCQ (Multiple-Choice Questions)

This post presents 70 multiple-choice questions (MCQs) designed for professionals and engineering students to test their understanding of JavaScript. Each question includes an answer and a clear explanation to reinforce key concepts and prepare for exams.

1. What is JavaScript?

a) A programming language for web development
b) A type of hardware
c) A database language
d) A styling language

Answer:

a) A programming language for web development

Explanation:

JavaScript is a popular programming language used primarily for web development. It allows developers to create dynamic content and interactive elements in web pages.

JavaScript runs on the client side, meaning it is executed in the user's browser, which enhances the functionality of a website without the need for server-side processing.

Example of a simple JavaScript code that displays "Hello, World!" in the browser console:


    console.log("Hello, World!");
    

2. Which of the following is the correct way to write a comment in JavaScript?

a) # This is a comment
b) // This is a comment
c)
d) /* This is a comment */

Answer:

b) // This is a comment

Explanation:

In JavaScript, single-line comments are written using // at the beginning of the comment. For multi-line comments, /* */ is used.

Example of both single-line and multi-line comments:


// This is a single-line comment

/*
 This is a multi-line comment
*/
    

Comments are ignored by the JavaScript engine and are used to explain the code or leave notes for other developers.

3. How do you declare a variable in JavaScript?

a) var, let, const
b) int, float, double
c) String, Number, Boolean
d) define, declare, constant

Answer:

a) var, let, const

Explanation:

In JavaScript, you can declare variables using var, let, or const. Each keyword has a different scope and behavior.

var is function-scoped, while let and const are block-scoped. const is used for declaring variables that should not be reassigned.

Example of declaring variables:


var x = 10;
let y = 20;
const z = 30;
    

4. Which of the following is used to output data to the browser console in JavaScript?

a) console.output()
b) console.log()
c) output.console()
d) browser.log()

Answer:

b) console.log()

Explanation:

To output data to the browser's console, you use the console.log() method in JavaScript. This is useful for debugging and displaying information during development.

Example:


console.log("Hello, World!");
    

5. What is the output of the following code:
console.log(typeof 42);
?

a) "number"
b) "string"
c) "boolean"
d) "undefined"

Answer:

a) "number"

Explanation:

The typeof operator is used to determine the data type of a given variable or value in JavaScript. In this case, 42 is a number, so the output is "number".

Example:


console.log(typeof 42); // Output: "number"
console.log(typeof "Hello"); // Output: "string"
console.log(typeof true); // Output: "boolean"
    

6. How do you write a conditional statement in JavaScript?

a) if (condition) { ... }
b) check (condition) { ... }
c) when (condition) { ... }
d) condition (if) { ... }

Answer:

a) if (condition) { ... }

Explanation:

In JavaScript, a conditional statement is written using if. It checks a condition and executes the code block if the condition is true.

Example:


if (x > 10) {
    console.log("x is greater than 10");
} else {
    console.log("x is not greater than 10");
}
    

7. What is the correct way to write a function in JavaScript?

a) function myFunction() { ... }
b) func myFunction() { ... }
c) def myFunction() { ... }
d) fn myFunction() { ... }

Answer:

a) function myFunction() { ... }

Explanation:

In JavaScript, functions are declared using the function keyword followed by the function name and a pair of parentheses. The code to be executed is written inside the curly braces.

Example:


function greet() {
    console.log("Hello, World!");
}
greet(); // Output: "Hello, World!"
    

8. How do you create an array in JavaScript?

a) var arr = [];
b) let arr = Array;
c) var arr = {};
d) let arr = newList();

Answer:

a) var arr = [];

Explanation:

In JavaScript, arrays are created using square brackets []. The elements are separated by commas.

Example:


var fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
    

9. Which of the following is the correct way to define an object in JavaScript?

a) var obj = { key: value };
b) var obj = [ key, value ];
c) var obj = "key = value";
d) var obj = (key, value);

Answer:

a) var obj = { key: value };

Explanation:

In JavaScript, objects are defined using curly braces {} and consist of key-value pairs. The keys represent properties, and the values can be any valid data type.

Example:


var person = {
    name: "John",
    age: 30,
    isStudent: false
};
console.log(person.name); // Output: "John"
    

10. What is the output of the following code: console.log("5" + 5);?

a) "55"
b) 10
c) NaN
d) 5

Answer:

a) "55"

Explanation:

When you use the + operator between a string and a number, JavaScript performs string concatenation. In this case, "5" (a string) is concatenated with 5 (a number), resulting in "55" (a string).

Example:


console.log("5" + 5); // Output: "55"
console.log(5 + 5); // Output: 10
    

11. What is the purpose of the Array.push() method in JavaScript?

a) To add elements to the end of an array
b) To remove elements from the array
c) To sort the elements in an array
d) To find the length of an array

Answer:

a) To add elements to the end of an array

Explanation:

The Array.push() method adds one or more elements to the end of an array and returns the new length of the array. It is useful when you need to append data to an existing array.

Example:


var fruits = ["Apple", "Banana"];
fruits.push("Orange");
console.log(fruits); // Output: ["Apple", "Banana", "Orange"]
    

12. What is the output of the following code: console.log(5 == "5");?

a) true
b) false
c) NaN
d) undefined

Answer:

a) true

Explanation:

In JavaScript, the double equals == performs type coercion, meaning it converts the operands to the same type before comparing. Here, "5" (a string) is converted to 5 (a number), so the comparison is true.

Example:


console.log(5 == "5"); // Output: true
console.log(5 === "5"); // Output: false (strict equality without type coercion)
    

13. How do you create a loop in JavaScript that runs 5 times?

a) for (let i = 0; i < 5; i++) { ... }
b) while (i < 5) { ... }
c) for (i <= 5) { ... }
d) loop (i < 5) { ... }

Answer:

a) for (let i = 0; i < 5; i++) { ... }

Explanation:

In JavaScript, the for loop is a common way to iterate a block of code a specified number of times. The syntax includes initialization, a condition, and an increment.

Example:


for (let i = 0; i < 5; i++) {
    console.log(i);
}
// Output: 0, 1, 2, 3, 4
    

14. What is the use of Array.length in JavaScript?

a) To find the number of elements in an array
b) To remove elements from an array
c) To sort elements in an array
d) To add elements to an array

Answer:

a) To find the number of elements in an array

Explanation:

The Array.length property returns the number of elements in an array. It is useful for determining the size of the array or for iterating over array elements.

Example:


var fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.length); // Output: 3
    

15. How do you write a function expression in JavaScript?

a) let myFunction = function() { ... }
b) function = myFunction() { ... }
c) def myFunction() { ... }
d) fn myFunction() { ... }

Answer:

a) let myFunction = function() { ... }

Explanation:

In JavaScript, a function expression is a function assigned to a variable. The function can be called using the variable name.

Example:


let greet = function() {
    console.log("Hello, World!");
};
greet(); // Output: "Hello, World!"
    

16. What is the purpose of the return statement in JavaScript?

a) To exit a function and return a value
b) To stop a loop
c) To repeat a function
d) To declare a variable

Answer:

a) To exit a function and return a value

Explanation:

The return statement is used inside a function to stop its execution and return a value to the calling code. If a function does not have a return statement, it returns undefined by default.

Example:


function add(a, b) {
    return a + b;
}
console.log(add(5, 10)); // Output: 15
    

17. What is the output of the following code: console.log(typeof null);?

a) "object"
b) "null"
c) "undefined"
d) "boolean"

Answer:

a) "object"

Explanation:

In JavaScript, the typeof operator returns "object" when applied to null. This is considered a quirk in JavaScript, as null is generally treated as a separate data type.

Example:


console.log(typeof null); // Output: "object"
    

18. How do you check if a variable is an array in JavaScript?

a) Array.isArray(variable)
b) variable.isArray()
c) typeof variable === "array"
d) variable instanceof Array

Answer:

a) Array.isArray(variable)

Explanation:

The method Array.isArray() is used to determine whether a variable is an array. It returns true if the variable is an array, and false otherwise.

Example:


let fruits = ["Apple", "Banana"];
console.log(Array.isArray(fruits)); // Output: true
    

19. What is the purpose of the Math.random() method in JavaScript?

a) To generate a random number between 0 and 1
b) To round numbers to the nearest integer
c) To generate a random integer
d) To find the square root of a number

Answer:

a) To generate a random number between 0 and 1

Explanation:

The Math.random() method generates a pseudo-random number between 0 (inclusive) and 1 (exclusive). It is often used in combination with other functions to generate random numbers within a specific range.

Example:


let randomNum = Math.random();
console.log(randomNum); // Output: A random number between 0 and 1
    

20. How do you convert a string to an integer in JavaScript?

a) parseInt()
b) parseFloat()
c) Number()
d) toString()

Answer:

a) parseInt()

Explanation:

The parseInt() function converts a string to an integer by parsing the string and returning the first integer value found. If the string does not contain a number, NaN (Not-a-Number) is returned.

Example:


let num = parseInt("123");
console.log(num); // Output: 123
    

21. What does the typeof operator return for an undefined variable?

a) "undefined"
b) "null"
c) "object"
d) "number"

Answer:

a) "undefined"

Explanation:

The typeof operator in JavaScript returns the string "undefined" when used on a variable that has not been assigned a value. This is different from null, which is an object.

For example:


let x;
console.log(typeof x); // Output: "undefined"
    

This helps in checking if a variable has been initialized before performing operations on it.

22. Which of the following methods is used to remove the last element from an array in JavaScript?

a) pop()
b) shift()
c) splice()
d) remove()

Answer:

a) pop()

Explanation:

The pop() method is used to remove the last element from an array in JavaScript. It modifies the original array and returns the removed element.

Example:


let fruits = ["Apple", "Banana", "Cherry"];
let lastFruit = fruits.pop();
console.log(fruits); // Output: ["Apple", "Banana"]
    

23. What will the Array.unshift() method do?

a) Add one or more elements to the beginning of an array
b) Remove the first element of an array
c) Add one or more elements to the end of an array
d) Sort the elements of an array

Answer:

a) Add one or more elements to the beginning of an array

Explanation:

The Array.unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Example:


let fruits = ["Banana", "Cherry"];
fruits.unshift("Apple");
console.log(fruits); // Output: ["Apple", "Banana", "Cherry"]
    

24. Which of the following statements will result in true when using the strict equality operator (===)?

a) 5 === "5"
b) null === undefined
c) true === 1
d) 5 === 5

Answer:

d) 5 === 5

Explanation:

The strict equality operator (===) compares both the value and type of two variables. The statement 5 === 5 returns true because both the value and type (number) are the same.

Other comparisons, like 5 === "5", return false because the types differ.

25. What is a callback function in JavaScript?

a) A function passed as an argument to another function
b) A function that returns multiple values
c) A function that runs in the background
d) A function that loops indefinitely

Answer:

a) A function passed as an argument to another function

Explanation:

A callback function is a function passed as an argument to another function and is invoked after the completion of that function. Callbacks are commonly used for asynchronous programming in JavaScript.

Example:


function greeting(name) {
    console.log("Hello " + name);
}

function processUserInput(callback) {
    let name = "John";
    callback(name);
}

processUserInput(greeting); // Output: "Hello John"
    

26. What will the console.log(null == undefined) statement output?

a) true
b) false
c) undefined
d) NaN

Answer:

a) true

Explanation:

In JavaScript, null and undefined are loosely equal (==), meaning they are treated as the same value in non-strict comparison, so null == undefined returns true.

However, they are not strictly equal (===), as their types are different.

27. What is the purpose of the setTimeout() function in JavaScript?

a) To delay the execution of a function by a specified amount of time
b) To execute a function repeatedly after a set interval
c) To set a function to run immediately
d) To terminate the execution of a function

Answer:

a) To delay the execution of a function by a specified amount of time

Explanation:

The setTimeout() function allows you to delay the execution of a function for a specified number of milliseconds. It only runs the function once after the delay.

Example:


setTimeout(function() {
    console.log("Hello, after 2 seconds!");
}, 2000);
    

28. Which of the following is true about const in JavaScript?

a) A variable declared with const cannot be reassigned
b) A variable declared with const is block-scoped
c) The value of a const variable can be an object or array
d) All of the above

Answer:

d) All of the above

Explanation:

Variables declared with const are block-scoped, meaning they are limited to the scope of the block in which they are defined. They cannot be reassigned, but if the value is an object or array, you can still modify the properties of the object or the elements of the array.

29. What is the output of the following code: console.log([] == false);?

a) true
b) false
c) undefined
d) NaN

Answer:

a) true

Explanation:

In JavaScript, an empty array [] is loosely equal (==) to false due to type coercion. When using ==, both operands are converted to the same type before comparison, resulting in true for [] == false.

30. Which of the following is the correct way to declare an arrow function in JavaScript?

a) let myFunc = () => { ... }
b) let myFunc => () { ... }
c) let myFunc = () { => ... }
d) let myFunc => { ... }

Answer:

a) let myFunc = () => { ... }

Explanation:

An arrow function in JavaScript is declared using the => syntax. It is a shorter way to write functions and has different behavior with the this keyword compared to regular functions.

Example:


let add = (a, b) => a + b;
console.log(add(5, 10)); // Output: 15
    

31. What will the console.log(NaN === NaN) statement output?

a) true
b) false
c) undefined
d) NaN

Answer:

b) false

Explanation:

In JavaScript, NaN (Not-a-Number) is a special value that represents an undefined or unrepresentable number. When comparing NaN with itself using ===, the result is false. This is because NaN is not considered equal to anything, even itself.

32. Which of the following is true about the this keyword in JavaScript arrow functions?

a) this refers to the global object
b) this is lexically bound
c) this refers to the parent function’s scope
d) this is dynamically bound

Answer:

b) this is lexically bound

Explanation:

In arrow functions, the this keyword is lexically bound, meaning it inherits this from the surrounding context where the function is defined. Unlike regular functions, this in arrow functions does not depend on how the function is called.

33. How can you convert a string to a number in JavaScript?

a) parseFloat()
b) parseInt()
c) Number()
d) All of the above

Answer:

d) All of the above

Explanation:

In JavaScript, you can convert a string to a number using parseFloat(), parseInt(), or Number(). Each has its specific use cases. parseInt() converts a string to an integer, parseFloat() converts it to a floating-point number, and Number() converts to either integer or float, depending on the input.

34. What will the console.log([] + []) statement output?

a) ""
b) []
c) undefined
d) NaN

Answer:

a) ""

Explanation:

In JavaScript, when two empty arrays are added together, the result is an empty string "". This is because JavaScript first converts the arrays to strings, and the string representation of an empty array is an empty string.

35. Which of the following methods is used to find the index of an element in an array in JavaScript?

a) indexOf()
b) findIndex()
c) find()
d) search()

Answer:

a) indexOf()

Explanation:

The indexOf() method returns the first index at which a given element can be found in an array, or -1 if the element is not present. It is useful for locating elements in arrays.

36. What is the purpose of the reduce() method in JavaScript arrays?

a) To reduce the length of an array
b) To apply a function to each element and accumulate the result
c) To remove duplicates from an array
d) To remove elements from an array

Answer:

b) To apply a function to each element and accumulate the result

Explanation:

The reduce() method executes a reducer function on each element of the array, resulting in a single output value. It is often used to sum or concatenate array elements, but it can also perform more complex transformations.

37. What is the difference between let and var in JavaScript?

a) let is block-scoped, while var is function-scoped
b) var is block-scoped, while let is function-scoped
c) let can be redeclared, while var cannot
d) There is no difference

Answer:

a) let is block-scoped, while var is function-scoped

Explanation:

The key difference between let and var is their scope. let is block-scoped, meaning it is only accessible within the block where it is declared, while var is function-scoped, meaning it is accessible throughout the function where it is declared.

38. What is the purpose of JSON.stringify() in JavaScript?

a) To convert a JavaScript object into a JSON string
b) To convert a JSON string into a JavaScript object
c) To sort the properties of a JavaScript object
d) To clone a JavaScript object

Answer:

a) To convert a JavaScript object into a JSON string

Explanation:

The JSON.stringify() method converts a JavaScript object or value into a JSON string. This is useful for storing or sending data in a text format, such as transmitting data between a server and web application.

39. How do you remove duplicates from an array in JavaScript?

a) Using Set()
b) Using Array.filter()
c) Using Array.reduce()
d) Using Array.map()

Answer:

a) Using Set()

Explanation:

One of the easiest ways to remove duplicates from an array in JavaScript is by using Set(). A Set object stores unique values, and you can convert the array to a Set and back to an array to remove duplicates.

40. What will the console.log(0.1 + 0.2 === 0.3) statement output?

a) true
b) false
c) undefined
d) NaN

Answer:

b) false

Explanation:

In JavaScript, the expression 0.1 + 0.2 === 0.3 evaluates to false due to floating-point precision issues. JavaScript uses floating-point arithmetic, which cannot precisely represent some decimal numbers, leading to small errors in calculations.

41. What is the purpose of Array.map() in JavaScript?

a) To create a new array by transforming every element in an array
b) To filter out elements from an array
c) To find the index of an element in an array
d) To modify the original array

Answer:

a) To create a new array by transforming every element in an array

Explanation:

The Array.map() method creates a new array populated with the results of calling a provided function on every element in the original array. The original array remains unchanged.

This method is often used for transforming data in a clean and concise way.

42. Which of the following will correctly check if a variable is an array in JavaScript?

a) Array.isArray(variable)
b) typeof variable === 'array'
c) variable.isArray()
d) variable instanceof Object

Answer:

a) Array.isArray(variable)

Explanation:

The most reliable way to check if a variable is an array in JavaScript is by using Array.isArray(variable). This method returns true if the variable is an array and false otherwise.

43. What is the output of the following code: console.log(typeof NaN);?

a) "undefined"
b) "number"
c) "object"
d) "NaN"

Answer:

b) "number"

Explanation:

In JavaScript, NaN stands for "Not-a-Number", but it is still considered a numeric value. When checking the type of NaN using typeof, the result is "number".

44. What is the purpose of the Array.filter() method in JavaScript?

a) To create a new array with elements that pass a test
b) To remove elements from the original array
c) To apply a function to every element of an array
d) To sort the elements of an array

Answer:

a) To create a new array with elements that pass a test

Explanation:

The Array.filter() method creates a new array with all elements that pass the test implemented by the provided function. It doesn't modify the original array.

45. Which method is used to convert JSON data to a JavaScript object?

a) JSON.parse()
b) JSON.stringify()
c) Object.assign()
d) Array.from()

Answer:

a) JSON.parse()

Explanation:

The JSON.parse() method is used to convert a JSON string into a JavaScript object. This is commonly used when receiving JSON data from an API or another external source.

46. What will the console.log([] == false) statement output?

a) true
b) false
c) undefined
d) NaN

Answer:

a) true

Explanation:

When comparing an empty array [] with false using the loose equality operator (==), JavaScript converts the array to a boolean and compares it with false, resulting in true.

47. What is a promise in JavaScript?

a) An object representing the eventual completion or failure of an asynchronous operation
b) A function that always resolves
c) A callback function
d) A synchronous operation

Answer:

a) An object representing the eventual completion or failure of an asynchronous operation

Explanation:

A promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation. It allows you to handle asynchronous tasks like fetching data or performing calculations in a non-blocking manner.

48. What does the finally() method do in a promise?

a) Executes a block of code after the promise is settled, regardless of the result
b) Executes a block of code only if the promise is resolved
c) Executes a block of code only if the promise is rejected
d) Cancels the promise

Answer:

a) Executes a block of code after the promise is settled, regardless of the result

Explanation:

The finally() method is called after a promise is either resolved or rejected. It is often used for cleanup actions that need to happen regardless of the outcome.

49. What will the console.log([1, 2, 3] + [4, 5, 6]) statement output?

a) "1,2,34,5,6"
b) "1,2,3,4,5,6"
c) [1,2,3,4,5,6]
d) NaN

Answer:

a) "1,2,34,5,6"

Explanation:

In JavaScript, when you use the + operator with arrays, it converts the arrays to strings and concatenates them. Therefore, the result is "1,2,34,5,6", a concatenated string of the two arrays.

50. What is the output of console.log(2 ** 3);?

a) 6
b) 8
c) 9
d) 4

Answer:

b) 8

Explanation:

The ** operator in JavaScript is used for exponentiation. The expression 2 ** 3 means "2 raised to the power of 3", which equals 8.

51. What is the purpose of the Object.assign() method in JavaScript?

a) To merge multiple objects into one
b) To copy properties from one object to another
c) To compare two objects
d) To delete properties from an object

Answer:

b) To copy properties from one object to another

Explanation:

The Object.assign() method is used to copy the properties from one or more source objects to a target object. It returns the target object with the combined properties. This is useful for shallow copying or merging objects.

52. What is the difference between call() and apply() methods in JavaScript?

a) call() takes individual arguments, while apply() takes an array of arguments
b) call() is used for synchronous code, while apply() is used for asynchronous code
c) call() executes a function immediately, while apply() creates a promise
d) Both are identical

Answer:

a) call() takes individual arguments, while apply() takes an array of arguments

Explanation:

Both call() and apply() methods invoke a function with a given this context and arguments. The difference lies in how arguments are passed: call() takes individual arguments, while apply() expects an array of arguments.

53. What is the output of the following code: console.log(typeof function(){});?

a) "object"
b) "function"
c) "undefined"
d) "object function"

Answer:

b) "function"

Explanation:

In JavaScript, the typeof operator returns "function" when applied to a function. Functions in JavaScript are a special type of object, but typeof identifies them as "function".

54. How do you create a deep copy of an object in JavaScript?

a) JSON.parse(JSON.stringify(object))
b) Object.assign()
c) object.slice()
d) Array.map()

Answer:

a) JSON.parse(JSON.stringify(object))

Explanation:

To create a deep copy of an object in JavaScript, you can use JSON.parse(JSON.stringify(object)). This method works by first converting the object into a JSON string and then parsing it back into a new object. This creates a new, independent copy of the original object.

55. What is an IIFE (Immediately Invoked Function Expression) in JavaScript?

a) A function that runs as soon as it is defined
b) A function that runs at the end of the script
c) A function that is called multiple times
d) A function that waits for a user event

Answer:

a) A function that runs as soon as it is defined

Explanation:

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs immediately after it is defined. This pattern is often used to create a private scope for variables and prevent them from polluting the global namespace.

56. How can you create a private variable in JavaScript?

a) Using closures
b) Using var outside a function
c) Using this keyword
d) Using let outside a function

Answer:

a) Using closures

Explanation:

Private variables in JavaScript can be created using closures. A closure is an inner function that has access to the outer function's variables, even after the outer function has returned. This allows private variables to be encapsulated within a function.

57. What is the purpose of Promise.all() in JavaScript?

a) To execute multiple promises in parallel and wait until all are resolved
b) To execute a promise multiple times
c) To create a new promise that resolves to the first settled promise
d) To cancel all promises

Answer:

a) To execute multiple promises in parallel and wait until all are resolved

Explanation:

The Promise.all() method takes an array of promises and returns a single promise that resolves when all of the promises have been resolved. If any promise in the array is rejected, the entire Promise.all() will reject with that reason.

58. What is the purpose of the async keyword in JavaScript?

a) To define a function that always returns a promise
b) To execute synchronous code
c) To delay the execution of a function
d) To wait for an event to happen

Answer:

a) To define a function that always returns a promise

Explanation:

The async keyword is used to define an asynchronous function, which always returns a promise. When an async function is called, it returns a promise, and you can use await to wait for the promise to resolve.

59. How does the await keyword work in JavaScript?

a) It pauses the execution of an async function until the promise is resolved or rejected
b) It returns a promise
c) It forces a function to execute synchronously
d) It runs a function immediately

Answer:

a) It pauses the execution of an async function until the promise is resolved or rejected

Explanation:

The await keyword is used inside an async function to pause execution until a promise is resolved or rejected. This allows asynchronous code to be written in a synchronous style.

60. What is the output of the following code: console.log([1, 2, 3] instanceof Array);?

a) true
b) false
c) undefined
d) null

Answer:

a) true

Explanation:

The instanceof operator checks if an object is an instance of a specific class. In this case, [1, 2, 3] is an array, so the result of [1, 2, 3] instanceof Array is true.

61. What is the purpose of the Proxy object in JavaScript?

a) To intercept and redefine fundamental operations on objects
b) To clone an object
c) To create a deep copy of an object
d) To delete properties from an object

Answer:

a) To intercept and redefine fundamental operations on objects

Explanation:

The Proxy object allows you to create a proxy for another object, which can intercept and redefine operations such as property access, assignment, and method invocation. Proxies provide a way to customize the behavior of fundamental JavaScript operations.

62. What is the difference between Object.freeze() and Object.seal() in JavaScript?

a) Object.freeze() makes an object immutable, while Object.seal() prevents new properties from being added
b) Object.freeze() allows new properties, while Object.seal() does not
c) Object.seal() removes properties, while Object.freeze() adds properties
d) They are identical

Answer:

a) Object.freeze() makes an object immutable, while Object.seal() prevents new properties from being added

Explanation:

The Object.freeze() method makes an object immutable, preventing changes to existing properties or the addition of new properties. The Object.seal() method prevents new properties from being added, but allows changes to existing properties.

63. How can you iterate over the properties of an object in JavaScript?

a) for...in loop
b) Object.keys()
c) Object.entries()
d) All of the above

Answer:

d) All of the above

Explanation:

In JavaScript, you can iterate over the properties of an object using the for...in loop, Object.keys() to get an array of keys, or Object.entries() to get an array of key-value pairs. Each method provides a different way of accessing an object's properties.

64. What is the purpose of Reflect in JavaScript?

a) To perform object operations like proxies without interception
b) To create a copy of an object
c) To modify the prototype of an object
d) To delete properties of an object

Answer:

a) To perform object operations like proxies without interception

Explanation:

The Reflect object provides methods for interceptable JavaScript operations, like setting or getting properties, without interception. It is often used in combination with proxies to handle operations when interception is not desired.

65. What is tail call optimization in JavaScript?

a) A method where the last function call is optimized to prevent stack overflow
b) A method that increases the call stack size
c) A technique to sort elements faster
d) A function to prevent recursion

Answer:

a) A method where the last function call is optimized to prevent stack overflow

Explanation:

Tail call optimization is a technique used in JavaScript to optimize recursive functions. When the last action of a function is a call to another function, JavaScript can optimize it to prevent stack overflow by reusing the stack frame for the next function call.

66. What is the difference between == and === in JavaScript?

a) == performs type coercion, while === checks both type and value
b) === performs type coercion, while == does not
c) Both perform type coercion
d) There is no difference

Answer:

a) == performs type coercion, while === checks both type and value

Explanation:

The == operator in JavaScript checks for equality after performing type coercion, meaning it converts operands to the same type before comparing them. The === operator, on the other hand, checks for strict equality, meaning it compares both type and value without type conversion.

67. What is the Set object used for in JavaScript?

a) To store unique values of any type
b) To create a collection of key-value pairs
c) To perform mathematical operations on arrays
d) To sort the elements in an array

Answer:

a) To store unique values of any type

Explanation:

The Set object in JavaScript allows you to store unique values of any type, whether primitive values or object references. A value in a Set may only occur once, making it useful for filtering duplicates.

68. How do you create a generator function in JavaScript?

a) By using the function* syntax
b) By using function generator()
c) By using the new Generator() keyword
d) By using the Promise() constructor

Answer:

a) By using the function* syntax

Explanation:

A generator function in JavaScript is defined using the function* syntax. Generator functions return a generator object that can be used to control the function's execution using the yield keyword to pause and resume execution.

69. What is the output of the following code: console.log([..."Hello"]);?

a) ["H", "e", "l", "l", "o"]
b) "Hello"
c) [["H", "e", "l", "l", "o"]]
d) undefined

Answer:

a) ["H", "e", "l", "l", "o"]

Explanation:

The spread operator (...) spreads the elements of an iterable (like a string) into individual elements. When applied to the string "Hello", it splits the string into an array of individual characters: ["H", "e", "l", "l", "o"].

70. What is the purpose of the WeakMap in JavaScript?

a) To store key-value pairs where the keys are objects and the values can be garbage collected if no other references exist
b) To store primitive values and prevent memory leaks
c) To create a map with weak references to keys
d) To store values that are automatically removed when their key is no longer referenced

Answer:

a) To store key-value pairs where the keys are objects and the values can be garbage collected if no other references exist

Explanation:

A WeakMap is a collection of key-value pairs where the keys are objects, and the values can be garbage collected if there are no other references to the keys. This makes WeakMap useful for managing memory when working with objects.

Comments