0% found this document useful (0 votes)
3K views

JavaSccript Quiz

The document contains questions about JavaScript concepts like syntax for external scripts, conditional statements, functions, arrays, objects, loops, and events. It covers topics like variables, data types, operators, JSON parsing and more.

Uploaded by

Laurence Svekis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views

JavaSccript Quiz

The document contains questions about JavaScript concepts like syntax for external scripts, conditional statements, functions, arrays, objects, loops, and events. It covers topics like variables, data types, operators, JSON parsing and more.

Uploaded by

Laurence Svekis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

Ultimate JavaScript Quiz

215 JavaScript Questions


Test Your Knowledge how many can you get correct?

What is the correct syntax for referring to an external script called "app.js"? 6
How do you write a conditional statement for executing some statements only if "i" is equal to 5? 7
How do you create a function in JavaScript? 7
What is the output of this code? 8
Which method is used to add an element at the end of an array? 8
How can a JavaScript variable be declared conditionally? 9
What will this code return? 9
What does the forEach method do in JavaScript? 10
What is the correct syntax for referring to an external script called app.js? 10
How do you write a conditional statement for executing some statements only if i is NOT equal to 5? 11
What is the purpose of the Array.prototype.map() method in JavaScript? 11
Which operator is used to assign a value to a variable? 12
How do you declare a JavaScript variable? 13
Which function of an Array object calls a function for each element in the array? 13
How do you round the number 7.25, to the nearest integer? 14
How do you find the number with the highest value of x and y? 14
What is the correct way to write a JavaScript array? 15
Which statement creates a new object in JavaScript? 15
How do you create a function in JavaScript? 16
Which method converts JSON data to a JavaScript object? 16
What will be the output of the following code? 17
How does a for loop start? 17
What does the this keyword refer to in a JavaScript method? 18
How can you detect the client's browser name in JavaScript? 19
What will the following code return? Boolean(10 > 9) 19
Which event occurs when the user clicks on an HTML element? 20
What is the correct syntax for referring to an external script called app.js that will NOT run until after the page has
loaded? 20
What does the this keyword refer to in a JavaScript method? 21
How can you detect the client's browser name in JavaScript? 21
What will the following code return? Boolean(10 > 9) 22
Which event occurs when the user clicks on an HTML element? 22

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
1
What is the correct syntax for referring to an external script called app.js that will NOT run until after the page has
loaded? 23
What is the purpose of the Array.prototype.reduce() method in JavaScript? 24
How do you declare a JavaScript asynchronous function? 24
What is a JavaScript Promise? 25
Which method is used to serialize an object into a JSON string in JavaScript? 25
What will the following code output to the console? 26
What is the purpose of the Array.prototype.reduce() method in JavaScript? 27
How do you declare a JavaScript asynchronous function? 27
What is a JavaScript Promise? 28
Which method is used to serialize an object into a JSON string in JavaScript? 28
What will the following code output to the console? 29
What does the splice method do in an array? 30
What will the following code return? 31
Which HTML attribute is used to define inline JavaScript? 31
What is the output of the following code? 32
Which method is used to remove the last element from an array? 32
How do you declare a constant variable in JavaScript? 33
Which of the following is a correct way to create an object in JavaScript? 33
Which of these is not a valid way to loop over an array in JavaScript? 34
What will the following code output? 35
What does the && operator do? 35
How do you find the length of a string str in JavaScript? 36
What is the correct syntax for creating a new Date object in JavaScript? 36
What will the following code output to the console? 37
Which of these keywords is used to define a block of code that will execute if an exception is thrown in a try block?
37
What will be the output of the following code snippet? 38
Which of the following is true about JavaScript? 39
What is the correct syntax to output something in the console in JavaScript? 39
How do you create a function in JavaScript? 40
How do you write a conditional statement in JavaScript? 40
What is the purpose of the Array.prototype.filter() method? 41
How can you add a comment in a JavaScript file? 41
How do you declare a JavaScript variable? 42
Which of the following is a way to define an object in JavaScript? 42
What is the use of parseInt function in JavaScript? 43
What does the === operator represent in JavaScript? 44
Which method is used to decode a URI in JavaScript? 44
What will the following code output? 45

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
2
Which one is NOT a valid JavaScript data type? 45
How do you write an 'if' statement in JavaScript to check if a variable a is NOT equal to 10? 46
What does the break statement do in JavaScript? 46
Which object in JavaScript is used to work with dates? 47
What is the output of 0.1 + 0.2 === 0.3? 47
What will the following code output? 48
How can you convert the string '123' to a number in JavaScript? 48
What will be logged to the console when the following code is executed? 49
Which method should be used to compare two dates in JavaScript? 50
What is the result of the following expression: null == undefined? 50
What is event delegation in JavaScript? 51
Which of the following is the correct way to create a new empty array in JavaScript? 51
How can you stop the execution of a setInterval method? 52
What is the output of the following code? 52
What does the bind() method in JavaScript do? 53
How do you find the largest number in a list of numbers in JavaScript? 54
What does the following code return? !!(function(){})() 54
What is the output of the following code? 55
What will the following code print? 55
Which method should you use to remove an element from the beginning of an array? 56
What is the output of this code? 56
What is a typical use case for an anonymous function in JavaScript? 57
What is the result of typeof NaN? 58
How do you clone an object in JavaScript? 58
What is event bubbling in JavaScript? 59
Which of the following is a valid type of function in JavaScript? 59
What is the default behavior of the this keyword in a function? 60
What does the following code return? Boolean(" ") 60
How do you write a JavaScript array? 61
What will the following code output? 61
Which statement is used to test for a specific condition in JavaScript? 62
Which JavaScript method is used for parsing integer values? 63
What will the following code print? 63
What is the output of the following code snippet? 64
How do you create a JavaScript Promise? 64
Which of these is a correct method to create a new array in JavaScript? 65
What is the output of console.log(0.1 + 0.2 == 0.3);? 65
How do you find the character at a specific index in a string in JavaScript? 66
How do you iterate over the properties of an object in JavaScript? 67
What will be the result of console.log(typeof undefined === typeof NULL);? 67

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
3
Which method is used to add an item to the beginning of an array? 68
What does the map() method do? 68
What will console.log('B' + 'a' + + 'a' + 'a'); output? 69
What is the use of the bind() method in JavaScript? 69
What is event bubbling in JavaScript? 70
What will be the output of the following code? 70
Which of the following is NOT a valid way to declare a JavaScript variable? 71
Which method would you use to remove an item from the end of an array and return that item? 72
How do you find the number with the highest value in a list of numbers? 72
What is the purpose of Array.prototype.forEach() method in JavaScript? 73
What will be the output of the following code? 73
How do you create a JavaScript Promise object? 74
Which one of these is used to check whether a property exists in an object? 75
What will this code output? 75
Which method is used to sort the elements of an array in place and return the sorted array? 76
How do you declare a JavaScript function? 76
What will the following code output? 77
Which method would you use to convert a JSON string into a JavaScript object? 77
How do you create a new object in JavaScript? 78
What is event delegation in JavaScript? 78
Which of these is a JavaScript data type? 79
What will this code output? 80
How can you check if an object is an array in JavaScript? 80
What is the purpose of the reduce() method in an array? 81
What is the correct syntax for adding comments in JavaScript? 82
What is the correct syntax for referring to an external script called "xxx.js"? 82
How do you create a variable with the numeric value 5? 83
Which of the following is a correct way to create an array in JavaScript? 83
What keyword is used to define a function in JavaScript? 84
How do you write an IF statement in JavaScript? 84
How do you find the element with the id "demo" in a web page? 85
How do you add an event handler in JavaScript? 85
How do you create an object in JavaScript? 86
What does the async keyword do? 86
Which statement is used to handle errors in JavaScript? 86
What is the purpose of template literals in JavaScript? 87
Which loop structure is not available in JavaScript? 87
Which of the following values is considered falsy in JavaScript? 88
What is a key feature of arrow functions in JavaScript? 88
What type of scope does JavaScript use? 89

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
4
What will be the output of console.log("5" + 3); in JavaScript? 89
Which statement is true about hoisting in JavaScript? 89
What is the initial state of a JavaScript Promise? 90
What is the purpose of "use strict" in JavaScript? 90
What does event bubbling mean in the context of JavaScript events? 91
What character is used to define a template string in JavaScript? 91
How can you access the property name of an object person? 92
What does Promise.all do? 92
Which keyword is used to define a class in JavaScript? 93
What is a closure in JavaScript? 93
What does JSON stand for? 94
What is the difference between let and const in JavaScript? 94
What does destructuring mean in JavaScript? 94
What does the map method do in JavaScript? 95
What will be the output of the following code? 95
What are default parameters in JavaScript functions? 96
What is the purpose of the JavaScript event loop? 96
What is a prototype in JavaScript? 97
What does the this keyword refer to in a JavaScript function? 97
What is a higher-order function in JavaScript? 98
What is the purpose of async/await in JavaScript? 98
In JavaScript, what are modules? 98
What do spread (...) operators do in JavaScript? 99
What is garbage collection in JavaScript? 99
What does the Document.querySelector() method do in the DOM API? 100
Which of the following is an instance of an Error object in JavaScript? 100
Which method is used to store data in the local storage in a web browser? 101
Which feature is unique to template literals in JavaScript? 101
What is the main role of a JavaScript engine in a web browser? 101
What is CORS in the context of web development? 102
What are WebSockets primarily used for in JavaScript? 102
What is the main purpose of service workers in web applications? 103
What is Cross-Site Scripting (XSS)? 103
What is the purpose of the console.log function in JavaScript? 104
Which object is used for making HTTP requests in JavaScript? 104
What is the purpose of the Intl object in JavaScript? 105
How do you select all paragraph elements in a document using JavaScript? 105
Which statement about JavaScript's setTimeout() function is true? 105
Which event fires whenever a form field loses focus? 106
What does the finally block do in a try...catch statement? 106

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
5
Which data type does JavaScript use for storing decimal values? 107
What is an IIFE (Immediately Invoked Function Expression) in JavaScript? 107
What is the purpose of regular expressions in JavaScript? 107
What is the scope of a variable declared with var inside a function in JavaScript? 108
What is the Singleton pattern in JavaScript? 108
What feature of HTML5 is used to draw graphics on a web page via JavaScript? 109
What is an API in the context of JavaScript web development? 109
What does the window object represent in a browser-based JavaScript environment? 110
Which method should you use to combine two arrays in JavaScript? 110
What is the purpose of the document.createElement() method in JavaScript? 111
What is the use of the === operator in JavaScript? 111
What is a callback function in JavaScript? 111
How do you check if an object is an array in JavaScript? 112
Which JavaScript method is used to write HTML output directly to a web page? 112
What is the main benefit of using Web Workers in JavaScript? 113
How can you dynamically change the style of an HTML element using JavaScript? 113
How do you prevent a form from submitting using JavaScript? 114
What is jQuery primarily used for? 114
How do you parse a JSON string in JavaScript? 115
Why is it recommended to avoid using global variables in JavaScript? 115
What does the navigator object in JavaScript represent? 115
Which JavaScript framework is primarily used for building user interfaces? 116
How do you remove an event listener from an element in JavaScript? 116
What method of the window object is used to display an alert box in JavaScript? 117
What is a RangeError in JavaScript? 117
What is the difference between getElementById and getElementsByClassName methods in JavaScript? 118

What is the correct syntax for referring to an external


script called "app.js"?

1. <script href="app.js">
2. <script name="app.js">
3. <script src="app.js">
4. <script file="app.js">

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
6
Answer: 3. <script src="app.js">
Explanation: The correct way to refer to an external JavaScript file is using the
<script> tag with the src attribute.

How do you write a conditional statement for executing


some statements only if "i" is equal to 5?

1. if i = 5
2. if i == 5 then
3. if (i == 5)
4. if i = 5 then
Answer: 3. if (i == 5)
Explanation: In JavaScript, the syntax for an if statement is if (condition).

How do you create a function in JavaScript?

1. function = myFunction()
2. function:myFunction()
3. function myFunction()
4. create myFunction()
Answer: 3. function myFunction()

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
7
Explanation: Functions in JavaScript are defined with the function keyword,
followed by a name, followed by parentheses ().

What is the output of this code?


console.log(typeof null);
A) "null"
B) "object"
C) "undefined"
D) "number"

Answer: B) "object"

Explanation: In JavaScript, null is considered a primitive value, but due to a


historical bug, typeof null returns "object". This bug has remained for
compatibility reasons.

Which method is used to add an element at the end of an


array?
A) array.push(element)
B) array.pop(element)
C) array.unshift(element)
D) array.shift(element)

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
8
Answer: A) array.push(element)

Explanation: array.push(element) adds one or more elements to the end of an


array and returns the new length of the array.

How can a JavaScript variable be declared conditionally?


A) var x if (condition)
B) if (condition) var x
C) var x = (condition) ? value1 : value2
D) condition(var x)

Answer: C) var x = (condition) ? value1 : value2

Explanation: This is a use of the ternary operator, which is a shorthand for the
if-else statement. It sets x to value1 if condition is true, and value2 if condition is
false.

What will this code return?


console.log(0.1 + 0.2 === 0.3);
A) true
B) false

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
9
C) TypeError
D) NaN

Answer: B) false

Explanation: This is due to floating-point precision in JavaScript. The result of 0.1 +


0.2 is actually slightly more than 0.3, thus not strictly equal (===) to 0.3.

What does the forEach method do in JavaScript?


A) It loops through an array and returns a new array.
B) It executes a function once for each array element.
C) It checks each element in an array to see if it meets a condition.
D) It applies a function against an accumulator and each element in the array
(from left to right) to reduce it to a single value.

Answer: B) It executes a function once for each array element.

Explanation: forEach is an Array method that is used to execute a provided


function once for each array element. It doesn’t return anything (undefined).

What is the correct syntax for referring to an external


script called app.js?
A) <script href="app.js">

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
10
B) <script name="app.js">
C) <script src="app.js">
D) <script file="app.js">

Answer: C) <script src="app.js">

Explanation: The correct way to refer to an external JavaScript file is using the
<script src="filename"> tag.

How do you write a conditional statement for executing


some statements only if i is NOT equal to 5?
A) if (i <> 5)
B) if i =! 5 then
C) if (i != 5)
D) if (i !== 5)

Answer: C) if (i != 5)

Explanation: In JavaScript, != is used to check if two values are not equal. !== is
also correct, but it checks both the value and the type, which isn't specified in the
question.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
11
What is the purpose of the Array.prototype.map()
method in JavaScript?
A) To iterate over each item in an array and modify the array in place.
B) To check whether at least one element in the array passes the test
implemented by the provided function.
C) To create a new array with the results of calling a provided function on every
element in the calling array.
D) To execute a reducer function on each element of the array, resulting in a single
output value.

Answer: C) To create a new array with the results of calling a provided function on
every element in the calling array.

Explanation: Array.prototype.map() is used to transform each element in the array


using the function provided and returns a new array with the transformed
elements.

Which operator is used to assign a value to a variable?


A) *
B) -
C) =
D) +

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
12
Answer: C) =

Explanation: In JavaScript, the = operator is used to assign values to variables.

How do you declare a JavaScript variable?


A) var name;
B) v name;
C) variable name;
D) new var name;

Answer: A) var name;

Explanation: var is the keyword used to declare a variable in JavaScript.

Which function of an Array object calls a function for


each element in the array?
A) forEach()
B) every()
C) forEvery()
D) each()

Answer: A) forEach()

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
13
Explanation: forEach() is a method that executes a provided function once for
each array element.

How do you round the number 7.25, to the nearest


integer?
A) Math.rnd(7.25)
B) Math.round(7.25)
C) round(7.25)
D) Math.floor(7.25)

Answer: B) Math.round(7.25)

Explanation: Math.round() is the correct method to round a number to the


nearest integer in JavaScript.

How do you find the number with the highest value of x


and y?
A) Math.ceil(x, y)
B) top(x, y)
C) Math.max(x, y)
D) ceil(x, y)

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
14
Answer: C) Math.max(x, y)

Explanation: Math.max() is a function that returns the largest of the zero or more
numbers given as input parameters.

What is the correct way to write a JavaScript array?


A) var colors = (1:"red", 2:"green", 3:"blue")
B) var colors = 1 = ("red"), 2 = ("green"), 3 = ("blue")
C) var colors = "red", "green", "blue"
D) var colors = ["red", "green", "blue"]

Answer: D) var colors = ["red", "green", "blue"]

Which statement creates a new object in JavaScript?


A) var obj = new Object();
B) var obj = new obj();
C) var obj = {};
D) Both A and C are correct.

Answer: D) Both A and C are correct.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
15
Explanation: In JavaScript, a new object can be created using either the new
Object() syntax or the object literal syntax {}. Both methods are widely used and
accepted.

How do you create a function in JavaScript?


A) function myFunction()
B) function:myFunction()
C) function = myFunction()
D) create myFunction()

Answer: A) function myFunction()

Explanation: Functions in JavaScript are defined with the function keyword,


followed by a name, followed by parentheses ().

Which method converts JSON data to a JavaScript object?


A) JSON.toString()
B) JSON.toObject()
C) JSON.parse()
D) JSON.stringify()

Answer: C) JSON.parse()

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
16
Explanation: JSON.parse() is used to parse a JSON string and construct the
JavaScript value or object described by the string.

What will be the output of the following code?

var x = 1;
function changeX() { x = 2; }
changeX();
console.log(x);
A) 1
B) 2
C) undefined
D) Error

Answer: B) 2

Explanation: The function changeX() changes the global variable x to 2. When


console.log(x) is called, it prints the updated value, which is 2.

How does a for loop start?


A) for (i = 0; i <= 5)

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
17
B) for (i <= 5; i++)
C) for (i = 0; i <= 5; i++)
D) for (i++)

Answer: C) for (i = 0; i <= 5; i++)

Explanation: The for loop in JavaScript is typically written with three optional
expressions: the initialization (i = 0), the condition (i <= 5), and the final expression
(i++).

What does the this keyword refer to in a JavaScript


method?
A) The global object
B) The object that owns the method
C) The document object
D) The window object

Answer: B) The object that owns the method

Explanation: In JavaScript, this refers to the object that owns the method, i.e., the
object the method is a method of. However, the value of this can change
depending on the context in which it's used.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
18
How can you detect the client's browser name in
JavaScript?
A) navigator.appName
B) browser.name
C) client.browser
D) window.browserName

Answer: A) navigator.appName

Explanation: The navigator.appName property returns the name of the browser.


However, it's important to note that this property can be unreliable due to
browser spoofing.

What will the following code return? Boolean(10 > 9)


A) true
B) false
C) NaN
D) undefined

Answer: A) true

Explanation: The expression 10 > 9 evaluates to true, and Boolean(true) is true.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
19
Which event occurs when the user clicks on an HTML
element?
A) onchange
B) onclick
C) onmouseover
D) onmouseclick

Answer: B) onclick

Explanation: The onclick event occurs when the user clicks on an element. It's one
of the most commonly used events in web pages.

What is the correct syntax for referring to an external


script called app.js that will NOT run until after the page
has loaded?
A) <script href="app.js" async>
B) <script src="app.js" defer>
C) <script src="app.js" async>
D) <script href="app.js" defer>

Answer: B) <script src="app.js" defer>

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
20
Explanation: Using the defer attribute in the <script> tag will ensure that the script
is executed after the page has finished parsing. Note that src is used to specify the
script source, not href.

What does the this keyword refer to in a JavaScript


method?
A) The global object
B) The object that owns the method
C) The document object
D) The window object

Answer: B) The object that owns the method

Explanation: In JavaScript, this refers to the object that owns the method, i.e., the
object the method is a method of. However, the value of this can change
depending on the context in which it's used.

How can you detect the client's browser name in


JavaScript?
A) navigator.appName
B) browser.name
C) client.browser

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
21
D) window.browserName

Answer: A) navigator.appName

Explanation: The navigator.appName property returns the name of the browser.


However, it's important to note that this property can be unreliable due to
browser spoofing.

What will the following code return? Boolean(10 > 9)


A) true
B) false
C) NaN
D) undefined

Answer: A) true

Explanation: The expression 10 > 9 evaluates to true, and Boolean(true) is true.

Which event occurs when the user clicks on an HTML


element?
A) onchange
B) onclick

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
22
C) onmouseover
D) onmouseclick

Answer: B) onclick

Explanation: The onclick event occurs when the user clicks on an element. It's one
of the most commonly used events in web pages.

What is the correct syntax for referring to an external


script called app.js that will NOT run until after the page
has loaded?
A) <script href="app.js" async>
B) <script src="app.js" defer>
C) <script src="app.js" async>
D) <script href="app.js" defer>

Answer: B) <script src="app.js" defer>

Explanation: Using the defer attribute in the <script> tag will ensure that the script
is executed after the page has finished parsing. Note that src is used to specify the
script source, not href.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
23
What is the purpose of the Array.prototype.reduce()
method in JavaScript?
A) To execute a reducer function on each element of the array, resulting in a single
output value.
B) To create a new array with the results of calling a provided function on every
element in the calling array.
C) To iterate over each item in an array and modify the array in place.
D) To check whether all elements in the array pass the test implemented by the
provided function.

Answer: A) To execute a reducer function on each element of the array, resulting


in a single output value.

Explanation: Array.prototype.reduce() method applies a function against an


accumulator and each element in the array (from left to right) to reduce it to a
single value.

How do you declare a JavaScript asynchronous function?


A) async function myFunc() {}
B) function async myFunc() {}
C) function myFunc() async {}
D) async() function myFunc() {}

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
24
Answer: A) async function myFunc() {}

Explanation: An asynchronous function in JavaScript is declared using the async


keyword before the function keyword and the function name.

What is a JavaScript Promise?


A) A function that calls another function after a set period of time.
B) An object that may produce a single value sometime in the future.
C) A JSON object returned by a web server.
D) A data structure that stores pairs of values.

Answer: B) An object that may produce a single value sometime in the future.

Explanation: A JavaScript Promise is an object representing the eventual


completion or failure of an asynchronous operation. It allows you to write
asynchronous code in a more manageable way.

Which method is used to serialize an object into a JSON


string in JavaScript?
A) JSON.stringify()
B) JSON.parse()
C) JSON.toObject()

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
25
D) JSON.toString()

Answer: A) JSON.stringify()

Explanation: JSON.stringify() method converts a JavaScript object or value to a


JSON string.

What will the following code output to the console?


console.log("5" + 3);
console.log("5" - 3);
A) "53" and 2
B) 8 and 2
C) "53" and "23"
D) 8 and "23"

Answer: A) "53" and 2

Explanation: In JavaScript, the + operator is used for both addition and


concatenation. If one of the operands is a string, it concatenates. However, the -
operator only performs subtraction, converting strings to numbers if possible.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
26
What is the purpose of the Array.prototype.reduce()
method in JavaScript?
A) To execute a reducer function on each element of the array, resulting in a single
output value.
B) To create a new array with the results of calling a provided function on every
element in the calling array.
C) To iterate over each item in an array and modify the array in place.
D) To check whether all elements in the array pass the test implemented by the
provided function.

Answer: A) To execute a reducer function on each element of the array, resulting


in a single output value.

Explanation: Array.prototype.reduce() method applies a function against an


accumulator and each element in the array (from left to right) to reduce it to a
single value.

How do you declare a JavaScript asynchronous function?


A) async function myFunc() {}
B) function async myFunc() {}
C) function myFunc() async {}
D) async() function myFunc() {}

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
27
Answer: A) async function myFunc() {}

Explanation: An asynchronous function in JavaScript is declared using the async


keyword before the function keyword and the function name.

What is a JavaScript Promise?


A) A function that calls another function after a set period of time.
B) An object that may produce a single value sometime in the future.
C) A JSON object returned by a web server.
D) A data structure that stores pairs of values.

Answer: B) An object that may produce a single value sometime in the future.

Explanation: A JavaScript Promise is an object representing the eventual


completion or failure of an asynchronous operation. It allows you to write
asynchronous code in a more manageable way.

Which method is used to serialize an object into a JSON


string in JavaScript?
A) JSON.stringify()
B) JSON.parse()
C) JSON.toObject()

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
28
D) JSON.toString()

Answer: A) JSON.stringify()

Explanation: JSON.stringify() method converts a JavaScript object or value to a


JSON string.

What will the following code output to the console?


console.log("5" + 3);
console.log("5" - 3);
A) "53" and 2
B) 8 and 2
C) "53" and "23"
D) 8 and "23"

Answer: A) "53" and 2

Explanation: In JavaScript, the + operator is used for both addition and


concatenation. If one of the operands is a string, it concatenates. However, the -
operator only performs subtraction, converting strings to numbers if possible.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
29
What does the splice method do in an array?
A) It replaces specified elements and/or adds new elements to the array.
B) It searches the array for specified items and returns their position.
C) It joins two or more arrays, and returns a new array.
D) It removes the last element of an array, and returns that element.

Answer: A) It replaces specified elements and/or adds new elements to the array.

Explanation: The splice method changes the contents of an array by removing or


replacing existing elements and/or adding new elements in place.

22. Which one of these is a JavaScript package manager?


A) Node.js
B) TypeScript
C) npm
D) JSON

Answer: C) npm

Explanation: npm (Node Package Manager) is the package manager for JavaScript,
allowing users to install and manage library dependencies for their JavaScript
applications.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
30
What will the following code return?

typeof("x" === "y");


A) "string"
B) "boolean"
C) "object"
D) "undefined"

Answer: B) "boolean"

Explanation: The expression "x" === "y" evaluates to a boolean (either true or
false). Therefore, typeof("x" === "y") returns "boolean".

Which HTML attribute is used to define inline JavaScript?


A) script
B) js
C) src
D) style

Answer: A) script

Explanation: Inline JavaScript code can be written inside HTML pages within a
<script> tag.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
31
What is the output of the following code?

let arr = [10, 20, 30, 40];


for (let i in arr) {
console.log(i);
}
A) 10, 20, 30, 40
B) 0, 1, 2, 3
C) undefined
D) Error

Answer: B) 0, 1, 2, 3

Explanation: The for...in loop in JavaScript iterates over the index or key of an array
(or object), not the elements themselves. Therefore, it logs the indices of the
array: 0, 1, 2, 3.

Which method is used to remove the last element from


an array?
A) pop()
B) push()

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
32
C) shift()
D) unshift()

Answer: A) pop()

Explanation: The pop() method removes the last element from an array and
returns that element, altering the length of the array.

How do you declare a constant variable in JavaScript?


A) let constant = value;
B) var constant = value;
C) constant = value;
D) const constant = value;

Answer: D) const constant = value;

Explanation: In modern JavaScript, a constant variable is declared using the const


keyword. It creates a variable whose value cannot be changed.

Which of the following is a correct way to create an


object in JavaScript?
A) var obj = { name: "John", age: 30 };

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
33
B) var obj = new Object(name: "John", age: 30);
C) var obj = Object.create("John", 30);
D) var obj = object("John", 30);

Answer: A) var obj = { name: "John", age: 30 };

Explanation: In JavaScript, objects are commonly created using the object literal
syntax {}, where properties and values are defined within braces.

Which of these is not a valid way to loop over an array in


JavaScript?
A) arr.forEach(function(item) { });
B) for (var item of arr) { }
C) for (var i in arr) { }
D) arr.loop(function(item) { });

Answer: D) arr.loop(function(item) { });

Explanation: JavaScript provides various ways to loop over arrays, such as forEach,
for...of, and for...in. However, arr.loop is not a standard method for looping.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
34
What will the following code output?

console.log(typeof NaN);
A) "number"
B) "NaN"
C) "undefined"
D) "object"

Answer: A) "number"

Explanation: NaN stands for "Not a Number," but paradoxically, in JavaScript,


typeof NaN is "number".

What does the && operator do?


A) It returns the first falsy value or the last value if none are found.
B) It returns the first truthy value or the last value if none are found.
C) It returns true if both values are true, otherwise false.
D) It concatenates two strings.

Answer: C) It returns true if both values are true, otherwise false.

Explanation: The && operator is a logical AND operator that returns true if both
operands are true, and false otherwise.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
35
How do you find the length of a string str in JavaScript?
A) str.length()
B) str.size()
C) str.length
D) length(str)

Answer: C) str.length

Explanation: In JavaScript, the length of a string is found using the .length


property, not a method.

What is the correct syntax for creating a new Date object


in JavaScript?
A) var date = Date(2020, 11, 20);
B) var date = new Date(2020, 11, 20);
C) var date = createDate(2020, 11, 20);
D) var date = new DateObject(2020, 11, 20);

Answer: B) var date = new Date(2020, 11, 20);

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
36
Explanation: The correct way to create a new Date object in JavaScript is with the
new Date() constructor.

What will the following code output to the console?

console.log(1 + "2" + "2");


A) "15"
B) "122"
C) "5"
D) "1222"

Answer: B) "122"

Explanation: In JavaScript, the + operator is also used for string concatenation.


Since one of the operands is a string, all the numbers are treated as strings, and
concatenation is performed.

Which of these keywords is used to define a block of


code that will execute if an exception is thrown in a try
block?
A) catch
B) finally

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
37
C) throw
D) error

Answer: A) catch

Explanation: The catch block is used to define a block of code that will be executed
if an exception is thrown in the associated try block.

What will be the output of the following code snippet?

let x = "10";
let y = 20;
console.log(x + y);
A) 30
B) "1020"
C) "30"
D) 10

Answer: B) "1020"

Explanation: In JavaScript, when a number is added to a string, the number is


converted to a string and then concatenated. Here, x is a string, so y is
concatenated to x as a string, resulting in "1020".

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
38
Which of the following is true about JavaScript?
A) JavaScript is a server-side only language.
B) JavaScript can be executed both on the client side and server side.
C) JavaScript is used for styling HTML pages.
D) JavaScript can only be written inside HTML documents.

Answer: B) JavaScript can be executed both on the client side and server side.

Explanation: JavaScript is a versatile language that can be executed on both the


client side (in browsers) and the server side (with environments like Node.js).

What is the correct syntax to output something in the


console in JavaScript?
A) console.output("Hello world");
B) console.log("Hello world");
C) print("Hello world");
D) document.write("Hello world");

Answer: B) console.log("Hello world");

Explanation: console.log() is the correct method to output something to the


console in JavaScript.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
39
How do you create a function in JavaScript?
A) function = myFunction()
B) function:myFunction()
C) function myFunction()
D) create myFunction()

Answer: C) function myFunction()

Explanation: In JavaScript, a function is defined with the function keyword,


followed by a name and parentheses, e.g., function myFunction().

How do you write a conditional statement in JavaScript?


A) if x = 5 then
B) if (x == 5)
C) if x == 5
D) if x = 5

Answer: B) if (x == 5)

Explanation: A conditional statement in JavaScript is written with the if keyword,


followed by the condition in parentheses, e.g., if (x == 5).

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
40
What is the purpose of the Array.prototype.filter()
method?
A) It creates a new array with elements that pass a test provided by a function.
B) It calls a function for each element in the array.
C) It modifies each element in an array based on a function.
D) It reduces an array to a single value.

Answer: A) It creates a new array with elements that pass a test provided by a
function.

Explanation: Array.prototype.filter() creates a new array with all elements that


pass the test implemented by the provided function.

How can you add a comment in a JavaScript file?


A) <!-- This is a comment -->
B) /* This is a comment */
C) // This is a comment
D) Both B and C

Answer: D) Both B and C

Explanation: In JavaScript, both // (for single-line comments) and /* ... */ (for


multi-line comments) are used for adding comments.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
41
How do you declare a JavaScript variable?
A) var name;
B) v name;
C) variable name;
D) new var name;

Answer: A) var name;

Explanation: Variables in JavaScript are declared using the var, let, or const
keyword, followed by the variable name, e.g., var name;.

Which of the following is a way to define an object in


JavaScript?
A) var car = {"make":"Toyota", "model":"Corolla"};
B) var car = new Object(); car.make = "Toyota"; car.model = "Corolla";
C) Both A and B
D) var car = (make: "Toyota", model: "Corolla");

Answer: C) Both A and B

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
42
Explanation: In JavaScript, objects can be defined either using object literal
notation (as in A) or by first creating an object and then adding properties to it (as
in B).

What is the use of parseInt function in JavaScript?


A) It parses a string and returns a floating point number.
B) It parses a string and returns an integer.
C) It converts integers into strings.
D) It checks if a value is an integer.

Answer: B) It parses a string and returns an integer.

Explanation: The parseInt function parses a string argument and returns an


integer of the specified radix (the base in mathematical numeral systems).

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


A) a.isArray()
B) Array.isArray(a)
C) typeof a === 'array'
D) a instanceof Array

Answer: B) Array.isArray(a)

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
43
Explanation: Array.isArray(a) is the recommended way to check if a variable is an
array. It returns true if the variable is an array, otherwise false.

What does the === operator represent in JavaScript?


A) Equality
B) Assignment
C) Strict Equality
D) Inequality

Answer: C) Strict Equality

Explanation: The === operator represents strict equality, meaning it checks for
equality of both value and type.

Which method is used to decode a URI in JavaScript?


A) decodeURI()
B) decodeURIComponent()
C) unescape()
D) Both A and B

Answer: D) Both A and B

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
44
Explanation: Both decodeURI() and decodeURIComponent() methods are used to
decode a Uniform Resource Identifier (URI) by replacing each escape sequence in
the encoded URI with the character that it represents.

What will the following code output?


console.log(typeof(undefined));
A) "undefined"
B) "object"
C) "null"
D) "string"

Answer: A) "undefined"

Explanation: The typeof operator returns a string indicating the type of the
unevaluated operand. For undefined, it returns the string "undefined".

Which one is NOT a valid JavaScript data type?


A) Undefined
B) Number
C) Boolean
D) Float

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
45
Answer: D) Float

Explanation: In JavaScript, there is no specific 'Float' data type. Numbers in


JavaScript can be integers or floating-point numbers.

How do you write an 'if' statement in JavaScript to check


if a variable a is NOT equal to 10?
A) if !(a == 10)
B) if (a != 10)
C) if a <> 10
D) if (a !== 10)

Answer: B) if (a != 10)

Explanation: if (a != 10) checks if the variable a is not equal to 10. The expression a
!== 10 also checks for strict inequality (considering the type).

What does the break statement do in JavaScript?


A) Breaks out of the current loop.
B) Terminates a switch statement.
C) Exits the current function.
D) Both A and B

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
46
Answer: D) Both A and B

Explanation: The break statement is used to exit from a loop or a switch


statement.

Which object in JavaScript is used to work with dates?


A) Date
B) DateTime
C) Time
D) Calendar

Answer: A) Date

Explanation: The Date object is used in JavaScript to work with dates and times.

What is the output of 0.1 + 0.2 === 0.3?


A) true
B) false
C) NaN
D) null

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
47
Answer: B) false

Explanation: Due to floating-point precision issues in JavaScript

What will the following code output?


console.log(typeof(42));
A) "number"
B) "integer"
C) "numeric"
D) "string"

Answer: A) "number"

Explanation: In JavaScript, the typeof operator returns the data type of its
operand. Here, typeof(42) returns "number" because 42 is a numeric literal.

How can you convert the string '123' to a number in


JavaScript?
A) Number('123')
B) parseInt('123')
C) parseFloat('123')
D) All of the above

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
48
Answer: D) All of the above

Explanation: In JavaScript, Number(), parseInt(), and parseFloat() can all be used


to convert a string to a number. Number('123') and parseInt('123') will both return
the number 123. parseFloat('123') will also return 123 but is typically used for
converting to floating-point numbers.

What will be logged to the console when the following


code is executed?
let x = 5;
let y = x++;
console.log(y);
A) 5
B) 6
C) undefined
D) Error

Answer: A) 5

Explanation: The postfix increment operator (x++) increments x, but returns the
value before incrementing. So, y is assigned the value 5, and x is then incremented
to 6.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
49
Which method should be used to compare two dates in
JavaScript?
A) compare()
B) compareTo()
C) equals()
D) getTime()

Answer: D) getTime()

Explanation: To compare two dates in JavaScript, you should convert them to their
numeric value (milliseconds since the Unix epoch) using the getTime() method.
Then you can compare these numeric values.

What is the result of the following expression: null ==


undefined?
A) true
B) false
C) TypeError
D) NaN

Answer: A) true

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
50
Explanation: In JavaScript, null and undefined are loosely equal, so null ==
undefined evaluates to true.

What is event delegation in JavaScript?


A) Attaching a single event listener to manage all events
B) A technique for handling events at a higher level in the DOM than the element
on which the event originated
C) Both A and B
D) None of the above

Answer: C) Both A and B

Explanation: Event delegation is a technique where you use a single event listener
on a parent element to manage all of its child elements' events, particularly useful
for handling dynamic elements or to optimize performance.

Which of the following is the correct way to create a new


empty array in JavaScript?
A) let arr = new Array();
B) let arr = [];
C) let arr = Array();
D) All of the above

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
51
Answer: D) All of the above

Explanation: In JavaScript, an empty array can be created using any of these


methods: new Array(), [], or simply calling Array().

How can you stop the execution of a setInterval method?


A) clearInterval()
B) stopInterval()
C) breakInterval()
D) pauseInterval()

Answer: A) clearInterval()

Explanation: The clearInterval() method is used to stop the executions set with the
setInterval() method.

What is the output of the following code?

let x = '5';
let y = x * 2;
console.log(y);

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
52
A) 10
B) "52"
C) NaN
D) TypeError

Answer: A) 10

Explanation: In JavaScript, when a string is involved in a mathematical operation


(other than addition), it tries to convert the string to a number. Here, '5' is
converted to 5, and then multiplied by 2 resulting in 10.

What does the bind() method in JavaScript do?


A) Connects two strings together
B) Ensures that a function always executes in the specified context
C) Binds an event to an element
D) None of the above

Answer: B) Ensures that a function always executes in the specified context

Explanation: The bind() method in JavaScript creates a new function that, when
called, has its this keyword set to the provided value. It's often used for handling
this inside callbacks or event handlers.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
53
How do you find the largest number in a list of numbers
in JavaScript?
A) Math.max(numbers)
B) Math.max.apply(null, numbers)
C) numbers.max()
D) numbers.findMax()

Answer: B) Math.max.apply(null, numbers)

Explanation: Math.max can't be directly applied to an array. However, using apply


with null as the first argument allows you to find the largest number in an array.

What does the following code return? !!(function(){})()


A) true
B) false
C) undefined
D) TypeError

Answer: A) true

Explanation: !! is used to convert the value on the right into a boolean. Since
functions are objects and objects are truthy in JavaScript, this expression returns
true.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
54
What is the output of the following code?
let num = 8;
let str = "8";
console.log(num === str);
A) true
B) false
C) TypeError
D) NaN

Answer: B) false

Explanation: The === operator checks for both value and type equality. Here, num
is a number and str is a string, so the result is false.

What will the following code print?


for (var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, i * 1000 );
}
A) 0, 1, 2, 3, 4
B) 5, 5, 5, 5, 5
C) 0, 1, 2, 3

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
55
D) 1, 2, 3, 4, 5

Answer: B) 5, 5, 5, 5, 5

Explanation: Due to JavaScript's closure and the fact that var declares a
function-scoped variable, each function created in the loop captures the same i
variable, which is 5 after the loop ends.

Which method should you use to remove an element


from the beginning of an array?
A) pop()
B) push()
C) shift()
D) unshift()

Answer: C) shift()

Explanation: shift() is the method used to remove the first element from an array
and return that removed element. This method changes the length of the array.

What is the output of this code?

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
56
console.log("1" - - "1");
A) 0
B) "11"
C) 2
D) "2"

Answer: C) 2

Explanation: In JavaScript, the - operator converts strings to numbers if possible


and performs subtraction. The double negative (- -) turns the second string into a
positive number, resulting in addition.

What is a typical use case for an anonymous function in


JavaScript?
A) Callbacks
B) Defining classes
C) Variable assignments
D) All of the above

Answer: A) Callbacks

Explanation: Anonymous functions are commonly used for callbacks, particularly


in asynchronous operations or event handlers.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
57
What is the result of typeof NaN?
A) "number"
B) "NaN"
C) "undefined"
D) "object"

Answer: A) "number"

Explanation: In JavaScript, NaN (Not a Number) is considered a numeric value, so


typeof NaN returns "number".

How do you clone an object in JavaScript?


A) let clone = Object.assign({}, obj);
B) let clone = [...obj];
C) let clone = clone(obj);
D) let clone = JSON.parse(JSON.stringify(obj));

Answer: A) let clone = Object.assign({}, obj);

Explanation: Object.assign() is used to clone an object. The first parameter is an


empty object {}, and the second parameter is the object to be cloned.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
58
What is event bubbling in JavaScript?
A) The event is directly handled at the captured phase.
B) An event propagates from the target element directly to the outermost
element.
C) An event propagates from the outermost element to the target element.
D) The event does not propagate in any direction.

Answer: B) An event propagates from the target element directly to the outermost
element.

Explanation: Event bubbling is a method of event propagation in the HTML DOM


where events propagate from the target element up to the outermost parent
element. This is the default behavior of events in JavaScript.

Which of the following is a valid type of function in


JavaScript?
A) Anonymous function
B) Named function
C) Immediate function
D) All of the above

Answer: D) All of the above

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
59
Explanation: JavaScript supports various function types, including anonymous
functions (functions without a name), named functions (functions with a specific
name), and immediately invoked function expressions (IIFE) or immediate
functions.

What is the default behavior of the this keyword in a


function?
A) Refers to the global object
B) Refers to the document object
C) Refers to the function itself
D) Refers to the window object

Answer: A) Refers to the global object

Explanation: In JavaScript, when used in a function, this refers to the global object.
In a browser, the global object is window, but the global object can be different in
other environments like Node.js.

What does the following code return? Boolean(" ")


A) true
B) false

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
60
C) undefined
D) NaN

Answer: A) true

Explanation: In JavaScript, a non-empty string, including a string with just a space,


is considered truthy. Therefore, Boolean(" ") returns true.

How do you write a JavaScript array?


A) var colors = 1 : ("red"), 2 : ("green"), 3 : ("blue");
B) var colors = (1:"red", 2:"green", 3:"blue");
C) var colors = "red", "green", "blue";
D) var colors = ["red", "green", "blue"];

Answer: D) var colors = ["red", "green", "blue"];

Explanation: An array in JavaScript is defined using square brackets [] and


elements in the array are separated by commas.

What will the following code output?

let x = 3;

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
61
let y = x++;
console.log(`x:${x}, y:${y}`);
A) x:4, y:3
B) x:3, y:4
C) x:4, y:4
D) x:3, y:3

Answer: A) x:4, y:3

Explanation: The post-increment operator (x++) first returns the value before
incrementing. So, y is assigned 3, and then x is incremented to 4.

Which statement is used to test for a specific condition in


JavaScript?
A) select
B) if
C) check
D) for

Answer: B) if

Explanation: The if statement is used to execute a block of code if a specified


condition is true.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
62
Which JavaScript method is used for parsing integer
values?
A) parseInt()
B) parseValue()
C) getInteger()
D) Number.parseInt()

Answer: A) parseInt()

Explanation: parseInt() is a function in JavaScript used to parse a string and return


an integer.

What will the following code print?

console.log(typeof null);
A) "null"
B) "undefined"
C) "object"
D) "number"

Answer: C) "object"

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
63
Explanation: This is a well-known quirk in JavaScript. Although null is not an
object, typeof null returns "object".

What is the output of the following code snippet?

const fruits = ["apple", "orange", "banana"];


console.log(fruits[3]);
A) "banana"
B) undefined
C) null
D) Error

Answer: B) undefined

Explanation: JavaScript arrays are zero-indexed, so fruits[3] tries to access the


fourth element, which does not exist in the array, resulting in undefined.

How do you create a JavaScript Promise?


A) new Promise()
B) Promise.create()
C) Promise()

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
64
D) new AsyncPromise()

Answer: A) new Promise()

Explanation: A JavaScript Promise is created using the new Promise() constructor,


which takes a function (executor) that is called with two arguments (resolve and
reject).

Which of these is a correct method to create a new array


in JavaScript?
A) var arr = [];
B) var arr = new Array();
C) var arr = Array();
D) All of the above

Answer: D) All of the above

Explanation: Each of these is a valid way to create an array in JavaScript. [] is the


array literal syntax, new Array() and Array() are constructors for creating an array.

What is the output of console.log(0.1 + 0.2 == 0.3);?


A) true
B) false

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
65
C) undefined
D) NaN

Answer: B) false

Explanation: This is a classic floating point problem in many programming


languages. 0.1 and 0.2 do not add up precisely to 0.3 due to the way numbers are
encoded in JavaScript.

How do you find the character at a specific index in a


string in JavaScript?
A) charAt(index)
B) charCodeAt(index)
C) indexOf(char)
D) characterAt(index)

Answer: A) charAt(index)

Explanation: The charAt() method returns the character at the specified index in a
string.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
66
How do you iterate over the properties of an object in
JavaScript?
A) for (let key in object)
B) object.forEach(key)
C) while (let key in object)
D) for (let key of object)

Answer: A) for (let key in object)

Explanation: The for...in loop is used to iterate over all enumerable properties of
an object.

What will be the result of console.log(typeof undefined


=== typeof NULL);?
A) true
B) false
C) TypeError
D) ReferenceError

Answer: B) false

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
67
Explanation: typeof undefined is "undefined", but NULL is not a valid identifier in
JavaScript (JavaScript is case-sensitive and null is the valid value). This results in
typeof NULL being "undefined" === "object", which is false.

Which method is used to add an item to the beginning of


an array?
A) push()
B) unshift()
C) shift()
D) pop()

Answer: B) unshift()

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

What does the map() method do?


A) It performs a function on each array element and returns a new array.
B) It checks each element for a condition and returns the first that matches.
C) It combines the elements of an array and returns a single value.
D) It filters an array based on a test function and returns a new array.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
68
Answer: A) It performs a function on each array element and returns a new array.

Explanation: The map() method creates a new array populated with the results of
calling a provided function on every element in the calling array.

What will console.log('B' + 'a' + + 'a' + 'a'); output?


A) "BaNaNa"
B) "Baaa"
C) "BaNaN"
D) SyntaxError

Answer: C) "BaNaN"

Explanation: This code is a tricky use of unary plus (+). The second 'a' is attempted
to be converted to a number, which results in NaN. The rest of the string
concatenation results in "BaNaN".

What is the use of the bind() method in JavaScript?


A) To bind a function to an object.
B) To permanently link a method to an object.
C) To copy a method from one object to another.
D) To delay the execution of a function.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
69
Answer: A) To bind a function to an object.

Explanation: The bind() method creates a new function, when invoked, has its this
keyword set to the provided value, and its arguments are any passed after the first
argument.

What is event bubbling in JavaScript?


A) A process where an event triggers the event handlers on its parent elements.
B) A process where an event triggers the event handlers on its child elements.
C) A process where an event stops after triggering its own handler.
D) A process where an event triggers all handlers in random order.

Answer: A) A process where an event triggers the event handlers on its parent
elements.

Explanation: Event bubbling is a mechanism in JavaScript where an event on a


child element propagates upwards, triggering handlers on its parent elements up
to the root.

What will be the output of the following code?


console.log(2 + '2');
A) 4

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
70
B) "22"
C) "4"
D) SyntaxError

Answer: B) "22"

Explanation: JavaScript performs automatic type coercion. In this case, the


number 2 is coerced into a string, and then concatenated with the string '2',
resulting in the string "22".

Which of the following is NOT a valid way to declare a


JavaScript variable?
A) var name;
B) let name;
C) const name;
D) dim name;

Answer: D) dim name;

Explanation: var, let, and const are the valid ways to declare variables in
JavaScript. dim is not a JavaScript keyword for declaring variables.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
71
Which method would you use to remove an item from
the end of an array and return that item?
A) pop()
B) push()
C) shift()
D) unshift()

Answer: A) pop()

Explanation: The pop() method removes the last element from an array and
returns that element. This method changes the length of the array.

How do you find the number with the highest value in a


list of numbers?
A) Math.max(numbers)
B) Math.max.apply(null, numbers)
C) numbers.max()
D) Math.highest(numbers)

Answer: B) Math.max.apply(null, numbers)

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
72
Explanation: Math.max.apply(null, numbers) allows you to find the highest
number in an array of numbers. The apply() method is used because Math.max
doesn't directly accept an array as an argument.

What is the purpose of Array.prototype.forEach() method


in JavaScript?
A) It modifies each item of the array based on a provided function.
B) It creates a new array with the results of calling a function for every array
element.
C) It executes a provided function once for each array element.
D) It reduces the array to a single value by executing a reducer function on each
element.

Answer: C) It executes a provided function once for each array element.

Explanation: forEach() method executes a provided function once for each


element in an array in ascending order. It doesn’t return anything.

What will be the output of the following code?


console.log(typeof undefined);
A) "null"
B) "undefined"

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
73
C) "object"
D) "boolean"

Answer: B) "undefined"

Explanation: The typeof operator returns a string indicating the type of the
unevaluated operand. Here, typeof undefined will return "undefined".

How do you create a JavaScript Promise object?


A) let promise = new Promise();
B) let promise = Promise();
C) let promise = Promise.create();
D) let promise = new createPromise();

Answer: A) let promise = new Promise();

Explanation: A Promise in JavaScript is created using the new Promise()


constructor, which takes a function (known as the executor function) as its
argument.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
74
Which one of these is used to check whether a property
exists in an object?
A) in
B) exists
C) hasOwnProperty()
D) Both A and C

Answer: D) Both A and C

Explanation: The in operator checks if a property exists in an object or its


prototype chain, whereas hasOwnProperty() method checks if a property exists
directly on the object.

What will this code output?


let a = [1, 2, 3];
let b = [1, 2, 3];
console.log(a == b);
A) true
B) false
C) TypeError
D) ReferenceError

Answer: B) false

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
75
Explanation: In JavaScript, arrays are reference types. Even if two arrays have
identical elements, they are not the same when compared as they refer to
different memory locations.

Which method is used to sort the elements of an array in


place and return the sorted array?
A) order()
B) sort()
C) arrange()
D) sequence()

Answer: B) sort()

Explanation: The sort() method sorts the elements of an array in place and returns
the sorted array. The default sort order is according to string Unicode code points.

How do you declare a JavaScript function?


A) function myFunc()
B) var myFunc = function()
C) let myFunc = () => {}
D) All of the above

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
76
Answer: D) All of the above

Explanation: In JavaScript, functions can be declared in various ways, including as


a function declaration (function myFunc()), a function expression (var myFunc =
function()), or using arrow function syntax (let myFunc = () => {}).

What will the following code output?


console.log(typeof NaN);
A) "NaN"
B) "number"
C) "undefined"
D) "object"

Answer: B) "number"

Explanation: Although NaN stands for "Not a Number," in JavaScript, it is


considered a numeric value, and therefore typeof NaN returns "number".

Which method would you use to convert a JSON string


into a JavaScript object?
A) JSON.parse()

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
77
B) JSON.stringify()
C) JSON.toObject()
D) JSON.toJavaScript()

Answer: A) JSON.parse()

Explanation: JSON.parse() is used to parse a JSON string and construct a JavaScript


value or object described by the string.

How do you create a new object in JavaScript?


A) var obj = {};
B) var obj = new Object();
C) var obj = Object.create(null);
D) All of the above

Answer: D) All of the above

Explanation: A new object in JavaScript can be created using object literal syntax
({}), the new Object() constructor, or the Object.create() method.

What is event delegation in JavaScript?


A) A process of handling events at a lower level before they bubble up

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
78
B) Assigning a single event listener to manage all events of a particular type
C) Handling an event at the target element level
D) A way to prevent events from bubbling up or capturing down

Answer: B) Assigning a single event listener to manage all events of a particular


type

Explanation: Event delegation is a technique of delegating event handling to a


parent element rather than individual child elements. It takes advantage of the
event bubbling phase.

Which of these is a JavaScript data type?


A) number
B) object
C) boolean
D) All of the above

Answer: D) All of the above

Explanation: JavaScript has multiple data types, including number, object, and
boolean.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
79
What will this code output?
var x = 1;
function foo() {
var x = 2;
console.log(x);
}
foo();
console.log(x);
A) 1, 2
B) 2, 1
C) 2, 2
D) 1, 1

Answer: B) 2, 1

Explanation: The function foo has its own local scope and logs 2. The global
variable x remains 1 and is logged outside the function.

How can you check if an object is an array in JavaScript?


A) typeof obj === 'array'
B) obj instanceof Array
C) Array.isArray(obj)
D) Both B and C

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
80
Answer: D) Both B and C

Explanation: To check if an object is an array, you can use obj instanceof Array or
Array.isArray(obj). Both are correct, although Array.isArray() is generally preferred
for its clarity and reliability.

What is the purpose of the reduce() method in an array?


A) To execute a provided function once for each array element, returning a single
output value.
B) To filter out elements in an array that do not pass a test in the provided
function.
C) To create a new array with each element being the result of the provided
function.
D) To iterate over each element of the array, executing a provided function
without returning a value.

Answer: A) To execute a provided function once for each array element, returning
a single output value.

Explanation: reduce() method applies a function against an accumulator and each


element in the array (from left to right) to reduce it to a single value.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
81
What is the correct syntax for adding comments in
JavaScript?
A) <!-- This is a comment -->
B) /* This is a comment */
C) // This is a comment
D) Both B and C

Answer: D) Both B and C

Explanation: In JavaScript, // is used for single-line comments, and /* ... */ is used


for multi-line comments. The <!-- ... --> syntax is for HTML comments.

Basic Syntax and Variables:

What is the correct syntax for referring to an external


script called "xxx.js"?

A) <script href="xxx.js">
B) <script name="xxx.js">
C) <script src="xxx.js">
D) <script file="xxx.js">
Answer: C

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
82
Explanation: In HTML, JavaScript code is inserted between <script> tags and the
'src' attribute is used to include an external script file.

How do you create a variable with the numeric value 5?

A) var num = 5;
B) num = 5;
C) var 5 = num;
D) num5 = var;
Answer: A
Explanation: The correct way to declare a variable in JavaScript is using the var, let,
or const keyword, followed by the variable name and its value.
Data Types and Structures:

Which of the following is a correct way to create an array


in JavaScript?
A) var colors = (1:"red", 2:"green", 3:"blue");
B) var colors = ["red", "green", "blue"];
C) var colors = 1 = ("red"), 2 = ("green"), 3 = ("blue");
D) var colors = "red", "green", "blue";
Answer: B
Explanation: Arrays in JavaScript are created using square brackets, with elements
separated by commas.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
83
Functions and Scope:

What keyword is used to define a function in JavaScript?


A) func
B) function
C) def
D) Func
Answer: B
Explanation: The function keyword is used to define a function in JavaScript.
Control Structures:

How do you write an IF statement in JavaScript?


A) if (i == 5)
B) if i = 5
C) if i == 5 then
D) if i = 5 then
Answer: A
Explanation: In JavaScript, the syntax for an if statement is if (condition).
DOM Manipulation:

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
84
How do you find the element with the id "demo" in a
web page?
A) document.getElement("demo");
B) document.getElementById("demo");
C) document.getElementsById("demo");
D) document.querySelector("#demo");
Answer: B
Explanation: document.getElementById("id") is the correct method to find an
element by its ID.
Events:

How do you add an event handler in JavaScript?


A) element.event = myFunction();
B) element.onEvent = myFunction();
C) element.addEventListener('event', myFunction);
D) element.attachEvent('onEvent', myFunction);
Answer: C
Explanation: The addEventListener method is used to set up a function to be
called whenever the specified event is delivered to the target.
Object-Oriented Programming:

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
85
How do you create an object in JavaScript?
A) var obj = new Object();
B) var obj = {};
C) Both A and B
D) None of the above
Answer: C
Explanation: Both new Object() and {} are valid ways to create an object in
JavaScript.
Asynchronous Programming:

What does the async keyword do?


A) Immediately invokes a function
B) Makes a function return a promise
C) Ensures a function runs synchronously
D) Pauses the execution of a function
Answer: B
Explanation: The async keyword is used before a function to make it return a
promise.
Error Handling:

Which statement is used to handle errors in JavaScript?


A) handle(error)

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
86
B) error()
C) try...catch
D) if...else
Answer: C
Explanation: The try...catch statement is used to catch errors in a block of code.
ES6 Features:

What is the purpose of template literals in JavaScript?


A) To connect strings and variables
B) To perform complex mathematical operations
C) To define multi-line strings
D) Both A and C
Answer: D
Explanation: Template literals allow for multi-line strings and can embed
expressions, making string concatenation more intuitive.

Which loop structure is not available in JavaScript?


A) for
B) while
C) do-while
D) repeat-until
Answer: D
Explanation: JavaScript supports for, while, and do-while loops, but there is no
repeat-until loop structure.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
87
Which of the following values is considered falsy in
JavaScript?
A) "0"
B) []
C) null
D) {}
Answer: C
Explanation: In JavaScript, falsy values include 0, "" (empty string), null, undefined,
NaN, and false. Arrays [] and objects {} are considered truthy.
Arrow Functions:

What is a key feature of arrow functions in JavaScript?


A) They do not have their own this context
B) They return the value automatically without return keyword if they contain a
single expression
C) They can be used as constructors
D) Both A and B
Answer: D
Explanation: Arrow functions don't have their own this context and automatically
return the value of a single expression without needing the return keyword.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
88
What type of scope does JavaScript use?
A) Lexical scope
B) Dynamic scope
C) Global scope
D) Local scope
Answer: A
Explanation: JavaScript uses lexical scoping, where the scope of a variable is
defined by its location within the source code.

What will be the output of console.log("5" + 3); in


JavaScript?
A) "53"
B) 8
C) TypeError
D) undefined
Answer: A
Explanation: In JavaScript, when you use the + operator with a string and a
number, the number is converted to a string and concatenated.

Which statement is true about hoisting in JavaScript?


A) Only variable declarations are hoisted to the top, not the initializations
B) Both variable declarations and initializations are hoisted

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
89
C) Functions are not hoisted
D) Hoisting applies to variables declared with let and const
Answer: A
Explanation: In JavaScript, variable declarations are hoisted to the top of their
scope, but their initializations are not. Function declarations are also hoisted, but
not the function expressions or arrow functions.

What is the initial state of a JavaScript Promise?


A) Resolved
B) Rejected
C) Pending
D) None of the above
Answer: C
Explanation: The initial state of a Promise is pending. It may then be fulfilled
(resolved) or failed (rejected).

What is the purpose of "use strict" in JavaScript?


A) Enables stricter parsing and error handling in your code
B) Prevents the use of global variables
C) Allows the use of advanced features like Promises and Generators
D) Automatically optimizes the performance of the script
Answer: A

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
90
Explanation: "use strict" enforces stricter parsing and error handling in JavaScript,
helping to avoid common coding mistakes and unsafe actions.
Event Bubbling and Capturing:

What does event bubbling mean in the context of


JavaScript events?
A) The event is first captured by the deepest element and then propagated to
outer elements
B) The event is directly handled by the element that caused it
C) The event is first captured by the outermost element and then propagated to
the inner elements
D) The event starts from the parent element and then goes to the child elements
Answer: A
Explanation: Event bubbling in JavaScript means that an event starts at the most
specific element (the deepest one), and then flows upward in the DOM tree,
triggering handlers as it goes.

What character is used to define a template string in


JavaScript?
A) Double quotes "
B) Single quotes '
C) Backticks ```

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
91
D) Forward slashes /
Answer: C
Explanation: Template strings in JavaScript are enclosed by backticks `. They can
contain placeholders which are indicated by ${expression} syntax.

How can you access the property name of an object


person?
A) person[name]
B) person.name
C) person->name
D) Both A and B
Answer: D
Explanation: In JavaScript, object properties can be accessed either using dot
notation (e.g., person.name) or bracket notation (e.g., person["name"]).

What does Promise.all do?


A) Resolves all promises passed to it as soon as the first one resolves
B) Resolves all promises passed to it as soon as the first one rejects
C) Resolves after all promises passed to it resolve, or rejects as soon as one of
them rejects
D) Resolves after all promises passed to it reject
Answer: C

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
92
Explanation: Promise.all waits for all promises to resolve or for any to reject. If all
resolve, it resolves with an array of the results. If any reject, it rejects with the
reason of the first promise that rejected.

Which keyword is used to define a class in JavaScript?


A) class
B) object
C) prototype
D) constructor
Answer: A
Explanation: The class keyword is used to define a class in JavaScript.

What is a closure in JavaScript?


A) A function and its lexical environment
B) An error-handling mechanism
C) The process of combining multiple functions into one
D) A type of loop
Answer: A
Explanation: A closure is a combination of a function and its lexical environment,
allowing it to access variables from an outer function after it has executed.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
93
What does JSON stand for?
A) JavaScript Object Notation
B) Java Standard Output Network
C) JavaScript Oriented Notation
D) Just a Simple Object Notation
Answer: A
Explanation: JSON stands for JavaScript Object Notation. It's a lightweight format
for storing and transporting data.

What is the difference between let and const in


JavaScript?
A) let is for immutable variables, while const is for mutable variables
B) let allows reassignment, while const does not
C) let is block-scoped, while const is function-scoped
D) No difference, they are interchangeable
Answer: B
Explanation: let allows you to declare variables that can be re-assigned, whereas
const is used for declaring variables that cannot be reassigned. Both are
block-scoped.

What does destructuring mean in JavaScript?


A) Breaking the script into smaller parts for better performance

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
94
B) An error that occurs when a script is not properly compiled
C) The process of assigning the properties of an object or array to variables using a
syntax that looks similar to array or object literals
D) Removing an element from an array or object
Answer: C
Explanation: Destructuring in JavaScript is a syntax for extracting multiple
properties from an array or object and assigning them to variables.

What does the map method do in JavaScript?


A) It changes the original array by applying a function to each element
B) It creates a new array with the results of calling a provided function on every
element in the calling array
C) It concatenates all elements of an array into a string
D) It searches an array for an element value and returns its position
Answer: B
Explanation: map creates a new array with the results of calling a function for
every array element. It does not modify the original array.

What will be the output of the following code?


console.log(x);
var x = 5;
A) undefined
B) 5

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
95
C) ReferenceError: x is not defined
D) null
Answer: A
Explanation: Due to variable hoisting in JavaScript, x is declared before it is used,
but its initialization is not hoisted. Therefore, the value of x is undefined when
console.log is called.

What are default parameters in JavaScript functions?


A) Parameters that are automatically passed if no arguments are provided
B) The first parameters in a function declaration
C) Parameters that are optional and can be omitted when calling the function
D) Predefined values assigned to function parameters
Answer: D
Explanation: Default parameters allow named parameters to be initialized with
default values if no value or undefined is passed.

What is the purpose of the JavaScript event loop?


A) To add new events to the JavaScript engine
B) To handle asynchronous operations and manage the execution order
C) To loop through array elements
D) To create new threads for parallel execution
Answer: B

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
96
Explanation: The JavaScript event loop is a mechanism that handles asynchronous
callbacks. It's responsible for executing the code, collecting and processing events,
and executing queued sub-tasks.

What is a prototype in JavaScript?


A) A preliminary version of a software application
B) The parent object from which other objects inherit properties
C) A special constructor function
D) The initial model on which all JavaScript objects are based
Answer: B
Explanation: In JavaScript, every object has a property called prototype from
which it inherits methods and properties.

What does the this keyword refer to in a JavaScript


function?
A) The function itself
B) The HTML element that received the event
C) The object that the function is a method of
D) The global object
Answer: C
Explanation: The value of this within a function depends on the context in which
the function is called, but generally, it refers to the object that the function is a
method of.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
97
What is a higher-order function in JavaScript?
A) A function that operates on other functions, either by taking them as
arguments or by returning them
B) A function that is executed at a higher priority level
C) A function that returns higher values than other functions
D) A function that can only be executed after the page has loaded
Answer: A
Explanation: Higher-order functions are functions that take other functions as
arguments or return them as results.

What is the purpose of async/await in JavaScript?


A) To pause the execution of a function until a promise resolves
B) To execute a function asynchronously
C) To immediately execute asynchronous code
D) To create a new thread like in multi-threading programming
Answer: A
Explanation: The async/await syntax is used to write asynchronous code that
behaves synchronously. async makes a function return a Promise, while await
makes a function wait for a Promise.

In JavaScript, what are modules?


A) Pre-written code libraries used for common tasks
B) A feature that allows splitting JavaScript programs into separate files
C) Functions that can be used to calculate mathematical operations

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
98
D) Built-in methods for manipulating strings and arrays
Answer: B
Explanation: JavaScript modules are a way to split a program into separate files,
allowing for better maintainability and reusability of code.

What do spread (...) operators do in JavaScript?


A) Concatenate arrays or objects
B) Spread the elements of an iterable (like an array) into individual elements
C) Increase the values of numeric elements in an array
D) Split a string into an array of characters
Answer: B
Explanation: The spread operator allows an iterable such as an array to be
expanded in places where zero or more arguments (for function calls) or elements
(for array literals) are expected.

What is garbage collection in JavaScript?


A) A process of removing old, unused code from a JavaScript program
B) A method to manage memory and clean up unreferenced objects
C) Deleting all variables set to null
D) A manual process of deallocating memory
Answer: B
Explanation: Garbage collection in JavaScript is the process of automatically
finding memory that is no longer in use and reclaiming it, ensuring efficient
memory management.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
99
What does the Document.querySelector() method do in
the DOM API?
A) Adds a new query to the document
B) Returns the first element within the document that matches the specified
group of selectors
C) Queries the server for updated content
D) Modifies the CSS of elements in the document
Answer: B
Explanation: Document.querySelector() returns the first Element within the
document that matches the specified selector or group of selectors. If no matches
are found, null is returned.

Which of the following is an instance of an Error object


in JavaScript?
A) SyntaxError
B) TypeError
C) ReferenceError
D) All of the above
Answer: D
Explanation: JavaScript has several built-in error constructors, such as SyntaxError,
TypeError, and ReferenceError, all of which create error object instances.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
100
Which method is used to store data in the local storage in
a web browser?
A) localStorage.store()
B) localStorage.save()
C) localStorage.setItem()
D) localStorage.put()
Answer: C
Explanation: The localStorage.setItem() method is used to store data in the
browser's local storage, allowing data to be stored across browser sessions.

Which feature is unique to template literals in JavaScript?


A) Ability to use single or double quotes for strings
B) Ability to span multiple lines without using special characters
C) Automatic conversion of all strings to uppercase
D) Restriction on the use of embedded expressions
Answer: B
Explanation: Template literals allow strings to span multiple lines without the need
for newline characters, and they can also contain placeholders for embedding
expressions.

What is the main role of a JavaScript engine in a web


browser?
A) To render HTML and CSS
B) To enable multimedia content

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
101
C) To parse and execute JavaScript code
D) To manage browser storage systems
Answer: C
Explanation: The JavaScript engine in a web browser is responsible for parsing and
executing JavaScript code, which enables dynamic content and interactive
features on web pages.

What is CORS in the context of web development?


A) A protocol for transferring data over different domains
B) A policy that allows or restricts resources to be requested from another domain
C) A method for encrypting data sent over the internet
D) A JavaScript framework for building user interfaces
Answer: B
Explanation: CORS (Cross-Origin Resource Sharing) is a policy used in web
browsers that controls whether resources like fonts, JavaScript, etc., can be
requested from another domain outside the domain from which the first resource
was served.

What are WebSockets primarily used for in JavaScript?


A) Storing data on the client-side
B) Enabling real-time, bi-directional communication between client and server
C) Displaying 3D graphics in the browser
D) Parsing and rendering HTML documents
Answer: B

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
102
Explanation: WebSockets provide a way to establish a persistent, real-time,
bi-directional communication channel between a client and a server, enabling
real-time data transfer.

What is the main purpose of service workers in web


applications?
A) To enable multi-threading in JavaScript
B) To act as a proxy server between web applications, the browser, and the
network
C) To enhance the graphical capabilities of a web page
D) To increase the computational power of JavaScript
Answer: B
Explanation: Service workers act as a proxy server between web applications, the
browser, and the network. They are primarily used for caching assets and enabling
functionality like push notifications and background sync.

What is Cross-Site Scripting (XSS)?


A) A method for optimizing JavaScript code
B) A security vulnerability that allows attackers to inject malicious scripts into
webpages viewed by other users
C) A technique for sharing scripts across multiple websites
D) A JavaScript framework for building secure web applications
Answer: B

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
103
Explanation: Cross-Site Scripting (XSS) is a security vulnerability that allows
attackers to inject malicious scripts into webpages, which can then be executed in
the context of other users' browsers.

What is the purpose of the console.log function in


JavaScript?
A) To display messages in the web browser's console for debugging purposes
B) To log user interactions with the web page
C) To record errors and exceptions in the server logs
D) To enhance the performance of JavaScript code
Answer: A
Explanation: The console.log function is used to output messages to the web
browser's console, primarily for debugging purposes.

Which object is used for making HTTP requests in


JavaScript?
A) HTTPClient
B) XMLHttpRequest
C) WebClient
D) FetchAPI
Answer: B, D
Explanation: Both XMLHttpRequest and the newer FetchAPI are used for making
HTTP requests in JavaScript. FetchAPI provides a more modern and powerful
approach.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
104
What is the purpose of the Intl object in JavaScript?
A) To provide language sensitive string comparison, number formatting, and date
and time formatting
B) To handle international domain names and URLs
C) To automatically translate web pages into different languages
D) To format JavaScript code according to international coding standards
Answer: A
Explanation: The Intl object is a namespace for the JavaScript Internationalization
API, which provides language-sensitive string comparison, number formatting, and
date and time formatting.

How do you select all paragraph elements in a document


using JavaScript?
A) document.getElement('p')
B) document.querySelectorAll('p')
C) document.getElementsByClassName('paragraph')
D) document.getElementsByTagName('p')
Answer: B
Explanation: document.querySelectorAll('p') selects all elements that match the
specified CSS selector, in this case, all <p> elements.

Which statement about JavaScript's setTimeout()


function is true?
A) It pauses the execution of the entire JavaScript engine for a specified time.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
105
B) It executes a function after waiting a specified number of milliseconds.
C) It is used to set the time for a JavaScript date object.
D) It calls a function continuously at specified time intervals.
Answer: B
Explanation: setTimeout() is used to execute a function once after a specified
duration in milliseconds.

Which event fires whenever a form field loses focus?


A) onchange
B) onfocus
C) onblur
D) onmouseleave
Answer: C
Explanation: The onblur event is fired when an element loses focus.

What does the finally block do in a try...catch statement?


A) It is executed after the try and catch blocks, but before any following
statements.
B) It runs only if the try block executes without any errors.
C) It contains conditions that must be true for the try block to execute.
D) It will execute only if an error is caught in the catch block.
Answer: A
Explanation: The finally block executes after the try and catch blocks, regardless of
whether an error occurred or not.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
106
Which data type does JavaScript use for storing decimal
values?
A) float
B) decimal
C) number
D) double
Answer: C
Explanation: JavaScript uses the number data type for all numbers, including
integers and decimals.

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 is executed at the end of the script.
C) A named function that is executed immediately after its creation.
D) A function that is automatically called when an error occurs.
Answer: A
Explanation: An IIFE is a JavaScript function that runs as soon as it is defined. It is
typically used to avoid polluting the global scope.

What is the purpose of regular expressions in JavaScript?


A) To perform complex mathematical calculations
B) To manipulate and animate HTML elements
C) To search, edit, or manipulate strings

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
107
D) To encode and decode JSON data
Answer: C
Explanation: Regular expressions are used in JavaScript for searching, editing, and
manipulating text strings.

What is the scope of a variable declared with var inside a


function in JavaScript?
A) Global scope
B) Block scope
C) Function scope
D) Local scope
Answer: C
Explanation: Variables declared with var inside a function are limited to function
scope.

What is the Singleton pattern in JavaScript?


A) A pattern that ensures a class has only one instance and provides a global point
of access to it.
B) A pattern where a function can generate instances of objects.
C) A pattern used for creating complex objects step by step.
D) A pattern that separates the construction of a complex object from its
representation.
Answer: A

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
108
Explanation: The Singleton pattern restricts a class to a single instance and
provides a global point of access to that instance.

What feature of HTML5 is used to draw graphics on a


web page via JavaScript?
A) <svg>
B) <canvas>
C) <graphics>
D) <art>
Answer: B
Explanation: The HTML5 <canvas> element is used to draw graphics on a web
page using JavaScript.

What is an API in the context of JavaScript web


development?
A) A set of classes for object-oriented programming
B) A server-side framework for creating web applications
C) An interface for letting your application communicate with other applications or
services
D) A tool for automating the build process of JavaScript projects
Answer: C

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
109
Explanation: In web development, an API (Application Programming Interface) is
an interface that allows your application to interact with external services or
systems, facilitating data exchange and integration.

What does the window object represent in a


browser-based JavaScript environment?
A) The JavaScript runtime environment
B) The background processes of a web page
C) The browser tab or window displaying the current web page
D) The server hosting the web page
Answer: C
Explanation: The window object represents the browser window or tab in which
the script is running, and it is the topmost object in the browser's document
object model (DOM).

Which method should you use to combine two arrays in


JavaScript?
A) append()
B) concat()
C) join()
D) merge()
Answer: B
Explanation: The concat() method is used to merge two or more arrays, returning
a new array without modifying the original arrays.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
110
What is the purpose of the document.createElement()
method in JavaScript?
A) To delete an existing HTML element
B) To update the content of an HTML element
C) To create a new HTML element
D) To find an existing HTML element
Answer: C
Explanation: The document.createElement() method creates a new HTML element
of the specified type.

What is the use of the === operator in JavaScript?


A) It assigns a value to a variable.
B) It compares two values for equality, without type conversion.
C) It concatenates two strings.
D) It increments a value.
Answer: B
Explanation: The === operator, also known as the strict equality operator,
compares two values for equality, ensuring that both the value and the type are
the same.

What is a callback function in JavaScript?


A) A function that is called at the start of another function
B) A function passed into another function as an argument, which is then invoked
inside the outer function to complete some kind of routine or action

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
111
C) A function that counts the number of times a function is called
D) A function that is automatically called whenever an error occurs
Answer: B
Explanation: In JavaScript, a callback function is a function passed into another
function as an argument, which is then executed at a specified point within the
outer function.

How do you check if an object is an array in JavaScript?


A) typeof object === 'array'
B) object instanceof Array
C) Array.isArray(object)
D) object.getType() === 'array'
Answer: C
Explanation: Array.isArray(object) is the preferred method to check if an object is
an array, as it returns true if the object is an array, and false otherwise.

Which JavaScript method is used to write HTML output


directly to a web page?
A) document.write()
B) console.log()
C) window.print()
D) response.send()
Answer: A

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
112
Explanation: document.write() is used to write directly to the HTML document.
However, it is generally not recommended for use in production code due to its
invasive nature.

What is the main benefit of using Web Workers in


JavaScript?
A) They enable multi-threading like capabilities by running scripts in background
threads
B) They improve the security of web applications
C) They are used for automating repetitive tasks in the browser
D) They help in storing large amounts of data locally
Answer: A
Explanation: Web Workers allow you to run JavaScript in background threads,
enabling parallel processing and improving the performance of web applications
that perform heavy calculations.

How can you dynamically change the style of an HTML


element using JavaScript?
A) document.getStyle().change()
B) element.style.property = 'value'
C) element.changeStyle('property', 'value')
D) style.setAttribute('property', 'value')
Answer: B

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
113
Explanation: In JavaScript, you can dynamically change the style of an HTML
element using element.style.property = 'value', where property is the CSS
property you want to change and value is the new style value.

How do you prevent a form from submitting using


JavaScript?
A) event.preventDefault()
B) form.stop()
C) submit.disable()
D) form.cancel()
Answer: A
Explanation: In an event handler, you can call event.preventDefault() to prevent
the default action of the event, such as submitting a form.

What is jQuery primarily used for?


A) Managing databases
B) Simplifying HTML document traversal, manipulation, and event handling
C) Compiling JavaScript to bytecode
D) High-performance server-side applications
Answer: B
Explanation: jQuery is a fast, small, and feature-rich JavaScript library designed to
simplify the client-side scripting of HTML, including DOM manipulation and event
handling.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
114
How do you parse a JSON string in JavaScript?
A) JSON.parse(jsonString)
B) JSON.stringify(jsonString)
C) JSON.decode(jsonString)
D) JSON.toObject(jsonString)
Answer: A
Explanation: JSON.parse(jsonString) is used to convert a JSON string into a
JavaScript object.

Why is it recommended to avoid using global variables in


JavaScript?
A) They can only store string values
B) They are slower to access than local variables
C) They can lead to code conflicts in larger applications
D) They are automatically deleted after script execution
Answer: C
Explanation: Global variables can lead to conflicts, especially in larger applications,
as different scripts might overwrite each other's variables.

What does the navigator object in JavaScript represent?


A) The active network connection
B) The browser's history

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
115
C) The operating system
D) The user's browser and its capabilities
Answer: D
Explanation: The navigator object contains information about the user's browser,
such as the name, version, and platform.

Which JavaScript framework is primarily used for building


user interfaces?
A) Node.js
B) Express.js
C) React
D) MongoDB
Answer: C
Explanation: React is a JavaScript library for building user interfaces, particularly
known for its efficient rendering and declarative style.

How do you remove an event listener from an element in


JavaScript?
A) element.removeEventListener(eventName, handlerFunction)
B) element.detachEvent(eventName, handlerFunction)
C) element.deleteEvent(eventName, handlerFunction)
D) element.off(eventName, handlerFunction)
Answer: A

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
116
Explanation: element.removeEventListener(eventName, handlerFunction) is used
to remove an event listener that was added with addEventListener.

What method of the window object is used to display an


alert box in JavaScript?
A) window.display()
B) window.message()
C) window.alert()
D) window.popup()
Answer: C
Explanation: window.alert() is used to display an alert dialog with a specified
message and an OK button.

What is a RangeError in JavaScript?


A) An error that occurs when a number is outside the bounds of its range
B) An error that occurs when trying to improperly access an array element
C) An error that occurs when a variable or parameter is not a valid type
D) An error that occurs when a function takes too long to execute
Answer: A
Explanation: A RangeError is thrown in JavaScript when a numeric variable or
parameter is outside of its valid range.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
117
What is the difference between getElementById and
getElementsByClassName methods in JavaScript?
A) getElementById returns a single element, while getElementsByClassName
returns a collection of elements
B) getElementById can select multiple elements, while getElementsByClassName
can only select one
C) getElementById is faster and more efficient than getElementsByClassName
D) getElementById applies to HTML elements only, while
getElementsByClassName applies to both HTML and XML elements
Answer: A
Explanation: getElementById retrieves a single element with the specified ID,
while getElementsByClassName returns a live HTMLCollection of all elements with
the specified class name.

Learn more about JavaScript with Examples and Source Code Laurence Svekis
Courses https://basescripts.com/
118

You might also like