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?
Answer:
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?
Answer:
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?
Answer:
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?
Answer:
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);
?
console.log(typeof 42);
Answer:
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?
Answer:
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?
Answer:
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?
Answer:
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?
Answer:
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);?
Answer:
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?
Answer:
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");?
Answer:
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?
Answer:
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?
Answer:
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?
Answer:
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?
Answer:
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);?
Answer:
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?
Answer:
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?
Answer:
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?
Answer:
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?
Answer:
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?
pop()
shift()
splice()
remove()
Answer:
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?
Answer:
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 (===
)?
5 === "5"
null === undefined
true === 1
5 === 5
Answer:
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?
Answer:
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?
true
false
undefined
NaN
Answer:
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?
Answer:
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?
const
cannot be reassignedconst
is block-scopedconst
variable can be an object or arrayAnswer:
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);?
true
false
undefined
NaN
Answer:
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?
let myFunc = () => { ... }
let myFunc => () { ... }
let myFunc = () { => ... }
let myFunc => { ... }
Answer:
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?
true
false
undefined
NaN
Answer:
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?
this
refers to the global objectthis
is lexically boundthis
refers to the parent function’s scopethis
is dynamically boundAnswer:
this
is lexically boundExplanation:
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?
parseFloat()
parseInt()
Number()
Answer:
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?
""
[]
undefined
NaN
Answer:
""
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?
indexOf()
findIndex()
find()
search()
Answer:
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?
Answer:
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?
let
is block-scoped, while var
is function-scopedvar
is block-scoped, while let
is function-scopedlet
can be redeclared, while var
cannotAnswer:
let
is block-scoped, while var
is function-scopedExplanation:
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?
Answer:
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?
Set()
Array.filter()
Array.reduce()
Array.map()
Answer:
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?
true
false
undefined
NaN
Answer:
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?
Answer:
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?
Array.isArray(variable)
typeof variable === 'array'
variable.isArray()
variable instanceof Object
Answer:
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);?
"undefined"
"number"
"object"
"NaN"
Answer:
"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?
Answer:
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?
JSON.parse()
JSON.stringify()
Object.assign()
Array.from()
Answer:
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?
true
false
undefined
NaN
Answer:
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?
Answer:
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?
Answer:
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?
"1,2,34,5,6"
"1,2,3,4,5,6"
[1,2,3,4,5,6]
NaN
Answer:
"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);?
6
8
9
4
Answer:
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?
Answer:
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?
call()
takes individual arguments, while apply()
takes an array of argumentscall()
is used for synchronous code, while apply()
is used for asynchronous codecall()
executes a function immediately, while apply()
creates a promiseAnswer:
call()
takes individual arguments, while apply()
takes an array of argumentsExplanation:
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(){});?
"object"
"function"
"undefined"
"object function"
Answer:
"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?
JSON.parse(JSON.stringify(object))
Object.assign()
object.slice()
Array.map()
Answer:
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?
Answer:
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?
var
outside a functionthis
keywordlet
outside a functionAnswer:
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?
Answer:
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?
Answer:
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?
async
function until the promise is resolved or rejectedAnswer:
async
function until the promise is resolved or rejectedExplanation:
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);?
true
false
undefined
null
Answer:
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?
Answer:
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?
Object.freeze()
makes an object immutable, while Object.seal()
prevents new properties from being addedObject.freeze()
allows new properties, while Object.seal()
does notObject.seal()
removes properties, while Object.freeze()
adds propertiesAnswer:
Object.freeze()
makes an object immutable, while Object.seal()
prevents new properties from being addedExplanation:
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?
for...in
loopObject.keys()
Object.entries()
Answer:
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?
Answer:
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?
Answer:
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?
==
performs type coercion, while ===
checks both type and value===
performs type coercion, while ==
does notAnswer:
==
performs type coercion, while ===
checks both type and valueExplanation:
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?
Answer:
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?
function*
syntaxfunction generator()
new Generator()
keywordPromise()
constructorAnswer:
function*
syntaxExplanation:
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"]);?
["H", "e", "l", "l", "o"]
"Hello"
[["H", "e", "l", "l", "o"]]
undefined
Answer:
["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?
Answer:
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
Post a Comment
Leave Comment