JS QB
JS QB
Q1. Which operator returns true if the two compared values are not equal?
<>
==!
!==
addTax = 50;
addTax(50);
addTax 50;
rate = 100;
Reference
Q6. When would the final statement in the code shown be logged to the console?
When would 'results shown' be logged to the console?
let modal = document.querySelector('#result');
setTimeout(function () {
modal.classList.remove('hidden');
}, 10000);
console.log('Results shown');
after 10 second
after results are received from the HTTP request
after 10000 seconds
immediately
Reference Javascript is synchronous and single threaded
Q7. Which snippet could you add to this code to print "food" to the console?
class Animal {
static belly = [];
eat() {
Animal.belly.push('food');
}
}
let a = new Animal();
a.eat();
console.log(/* Snippet Here */); //Prints food
a.prototype.belly[0]
Object.getPrototype0f (a).belly[0]
Animal.belly[0]
a.belly[0]
E
for (var j = 1; j <= 4; j++) {
setTimeout(function () {
console.log(j);
}, j * 1000);
}
1. Reference setTimeout
2. Reference immediately invoked anonymous functions
Q9. How does a function create a closure?
It reloads the document whenever the value changes.
It returns a reference to a variable in its parent scope.
It completes execution without returning.
It copies a local variable to the global scope.
Reference
Q10. Which statement creates a new function called discountPrice?
A
let discountPrice(price) {
return price * 0.85;
};
Storm()
undefined
'rain'
'snow'
Reference prototype chain
Q12. You need to match a time value such as 12:00:32. Which of the following
regular expressions would work for your code?
/[0-9]{2,}:[0-9]{2,}:[0-9]{2,}/
/\d\d:\d\d:\d\d/
/[0-9]+:[0-9]+:[0-9]+/
/ : : /
NOTE: The first three are all partially correct and will match digits, but the second
option is the most correct because it will only match 2 digit time values (12:00:32).
The first option would have worked if the repetitions range looked like [0-9]{2} ,
however because of the comma [0-9]{2,} it will select 2 or more digits
(120:000:321). The third option will any range of time digits, single and multiple
(meaning 1:2:3 will also match).
More resources:
1. Repeating characters
2. Kleene operators
Q13. What is the result in the console of running this code?
'use strict';
function logThis() {
this.desc = 'logger';
console.log(this);
}
new logThis();
undefined
window
{desc: "logger"}
function
roadTypes.2
roadTypes[3]
roadTypes.3
roadTypes[2]
Reference accessing javascript arrays
Q15. What is the result of running this statement?
console.log(typeof 42);
'float'
'value'
'number'
'integer'
object
target
source
Reference DOM events
Q17. You're adding error handling to the code shown. Which code would you
include within the if statement to specify an error message?
function addNumbers(x, y) {
if (isNaN(x) || isNaN(y)) {
}
}
JSON.parse()
JSON.toObject()
JSON.stringify()
12345
1234
01234
012345
Reference javascript for loops
Q21. Which Object method returns an iterable that can be used to iterate over the
properties of an object?
Object.get()
Object.loop()
Object.each()
Object.keys()
101
3
4
100
Q23. What is one difference between collections created with Map and collections
created with Object?
You can iterate over values in a Map in their insertion order.
You can count the records in a Map with a single method call.
Keys in Maps can be strings.
You can access values in a Map without iterating over the whole collection.
Explanation: Map.prototype.size returns the number of elements in a Map,
whereas Object does not have a built-in method to return its size.
Reference map methods javascript
Q24. What is the value of dessert.type after executing this code?
const dessert = { type: 'pie' };
dessert.type = 'pudding';
pie
The code will throw an error.
pudding
undefined
Reference working with js objects
Q25. 0 && hi
ReferenceError
true
0
false
Reference boolean logic
Q26. Which of the following operators can be used to do a short-circuit
evaluation?
++
--
==
||
Student.prototype = Person;
Student.prototype = Person();
var
let
Boolean("")
Boolean(NaN)
Boolean("false")
catch
function
array
x.get('Y')
x.Y
x.Y()
x.get().Y
Reference getters
Q34. What is the result of running this code?
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
import 'lodash' as _;
true
undefined
[]
false
Reference arrays in js are objects
Q39. What type of function can have its execution suspended and then resumed
at a later point?
Generator function
Arrow function
Async/ Await function
Promise function
Reference what are generators in nodejs
Q40. What will this code print?
var v = 1;
var f1 = function () {
console.log(v);
};
var f2 = function () {
var v = 2;
f1();
};
f2();
2
1
Nothing - this code will throw an error.
undefined
Reference closures in js / nested functions
Q41. Which statement is true about Functional Programming?
Every object in the program has to be a function.
Code is grouped with the state it modifies.
Date fields and methods are kept in units.
Side effects are not allowed.
Reference functional programming
Q42. Your code is producing the error: TypeError: Cannot read property 'reduce'
of undefined. What does that mean?
You are calling a method named reduce on an object that's declared but has no
value.
You are calling a method named reduce on an object that does not exist.
You are calling a method named reduce on an empty array.
You are calling a method named reduce on an object that's has a null value.
Explanation: You cannot invoke reduce on undefined object... It will throw
(yourObject is not Defined...)
Q43. How many prototype objects are in the chain for the following array?
let arr = [];
3
2
0
1
Reference array prototype
Q44. Which choice is not a unary operator?
typeof
delete
instanceof
void
conditional
block
global
function
Reference block vs function scope
Q46. What will the value of y be in this code:
const x = 6 % 2;
const y = x ? 'One' : 'Two';
One
undefined
TRUE
Two
Reference ternary operator js
Q47. Which keyword is used to create an error?
throw
exception
catch
error
Document.querySelector('class.pull')
document.querySelector('.pull');
Document.querySelector('pull')
Document.querySelector('#pull')
10
true
false
0
Reference javascript conditionals
Q52. What is the result in the console of running the code shown?
var start = 1;
function setEnd() {
var end = 10;
}
setEnd();
console.log(end);
10
0
ReferenceError
undefined
Reference
Q53. What will this code log in the console?
function sayHello() {
console.log('hello');
}
console.log(sayHello.prototype);
undefined
"hello"
an object with a constructor property
an error message
Reference prototypes
Q54. Which collection object allows unique value to be inserted only once?
Object
Set
Array
Map
Reference javascript sets
Q55. What two values will this code print?
function printA() {
console.log(answer);
var answer = 1;
}
printA();
printA();
1 then 1
1 then undefined
undefined then 1
Reference
Q56. How does the forEach() method differ from a for statement?
forEach allows you to specify your own iterator, whereas for does not.
forEach can be used only with strings, whereas for can be used with additional
data types.
forEach can be used only with an array, whereas for can be used with additional
data types.
for loops can be nested; whereas forEach loops cannot.
Reference Differences between forEach and for loop
Q57. Which choice is an incorrect way to define an arrow function that returns an
empty object?
=> ({})
=> {}
=> { return {};}
=> (({}))
Reference arrow functions
Q58. Why might you choose to make your code asynchronous?
to start tasks that might take some time without blocking subsequent tasks from
executing immediately
to ensure that tasks further down in your code are not initiated until earlier tasks
have completed
to make your code faster
to ensure that the call stack maintains a LIFO (Last in, First Out) structure
EXPLANATION: "to ensure that tasks further down in your code are not
initiated until earlier tasks have completed" you use the normal
(synchronous) flow where each command is executed sequentially.
Asynchronous code allows you to break this sequence: start a long running
function (AJAX call to an external service) and continue running the rest
of the code in parallel.
3 == '3'
3 != '3'
3 === '3'
1. Reference booleans
2. Reference 2 - booleans
Q60. Which of these is a valid variable name?
5thItem
firstName
grand total
function
Reference coding conventions
Q61. Which method cancels event default behavior?
cancel()
stop()
preventDefault()
prevent()
getNode()
querySelector()
appendChild()
Reference Node interface
Q63. What statement can be used to skip an iteration in a loop?
break
pass
skip
continue
a, b => c
{ a, b } => c
# This is a comment
\\ This is a comment
// This is a comment
4
10
6
5
Reference ++x vs x++
Q70. You've written the event listener shown below for a form button, but each
time you click the button, the page reloads. Which statement would stop this from
happening?
button.addEventListener(
'click',
function (e) {
button.className = 'clicked';
},
false,
);
e.blockReload();
button.preventDefault();
button.blockReload();
e.preventDefault();
Document.querySelectorAll('<img>')
Document.querySelectorAll('img')
Document.querySelector('<img>')
function
undefined
Function.prototype
window
Reference what is the javascript window
Q77. Which class-based component is equivalent to this function component?
const Greeting = ({ name }) => <h1>Hello {name}!</h1>;
Q78. Which class-based lifecycle method would be called at the same time as this
effect Hook?
useEffect(() => {
// do things
}, []);
componentWillUnmount
componentDidUpdate
render
componentDidMount
Reference
Q79. What is the output of this code?
var obj;
console.log(obj);
{}
undefined
null
calculate(50);
new TaxCalculator().calculate($50);
TaxCalculator.calculate(50);
new TaxCalculator().calculate(50);
Reference functions in javascript
Q81. What is wrong with this code?
const foo = {
bar() {
console.log('Hello, world!');
},
name: 'Albert',
age: 26,
};
.
I
Javascript!
love
.
love
I
Javascript!
The output may change with each execution of code and cannot be determined.
.
I
love
Javascript!
Reference https://developer.mozilla.org/en-
US/docs/Web/API/setTimeout#reasons_for_delays_longer_than_specified especially
see the 'late timeouts' section.
Q83. What will this code log to the console?
const foo = [1, 2, 3];
const [n] = foo;
console.log(n);
1
undefined
NaN
Nothing--this is not proper JavaScript syntax and will throw an error.
Reference array deconstruction
Q84. How do you remove the property name from this object?
const foo = {
name: 'Albert',
};
overloading
closure
currying
overriding
Reference currying
Q87. Which tag pair is used in HTML to embed JavaScript?
<script></script>
<js></js>
<javascript></javascript>
<code></code>
["Amazon","Borneo","Cerrado","Congo"]
["Cerrado", "Congo"]
["Congo"]
["Amazon","Borneo"]
const {one,two,three,four,five}=numbers
const [one,two,three,four,five]=[numbers]
const {one,two,three,four,five}={numbers}
const obj2 = {
...obj,
a: 0,
};
console.log(obj2.a, obj2.b);
animals.reverse();
animals.shift();
animals.pop();
undefined
One
true
Two
Note: this question is same with Q46. Reference ternary operator js
Q96. How would you access the word It from this multidimensional array?
let matrix = [["You","Can"],["Do","It"],["!","!","!"]];
matrix[1[2]]
matrix[1][1]
matrix[1,2]
matrix[1][2]
Q97. What does this code do?
const animals = ['Rabbit', 'Dog', 'Cat'];
animals.unshift('Lizard');
93
12
66
633
Reference type coercion
Q99. Which statement can take a single expression as input and then look through
a number of choices until one that matches that value is found?
else
when
if
switch
Reference switch
Q100. Which statement prints "roar" to the console?
var sound = 'grunt';
var bear = { sound: 'roar' };
function roar() {
console.log(this.sound);
}
bear.bind(roar);
roar.bind(bear);
roar.apply(bear);
bear[roar]();
1. Reference Apply
2. Reference this
3. Reference bind
Q101. Which choice is a valid example of an arrow function, assuming c is defined
in the outer scope?
a, b => { return c; }
a, b => c
{ a, b } => c
(a,b) => c
console.log([...arr1, ...arr2]);
[2, 3, 4, 5, 6, 7]
[3,5,7,2,4,6]
[3, 5, 7, 2, 4, 6]
[2, 4, 6, 3, 5, 7]
Reference spread syntax
Q104. Which method call is chained to handle a successful response returned by
fetch() ?
done()
then()
finally()
catch()
Reference fetch
Q105. Which choice is not an array method?
array.slice()
array.shift()
array.push()
array.replace()
string
array
Boolean
object
//JavaScript
document.querySelectorAll('div').forEach((e) => {
e.onclick = (e) => console.log(e.currentTarget.id);
});
CBA
A
C
ABC
1. Reference query selector
2. Reference events
Q109. What will this code log to the console?
const myNumbers = [1, 2, 3, 4, 5, 6, 7];
const myFunction = (arr) => {
return arr.map((x) => x + 3).filter((x) => x < 7);
};
console.log(myFunction(myNumbers));
[4,5,6,7,8,9,10]
[4,5,6,7]
[1,2,3,4,5,6]
[4,5,6]
2
4
6
8
Reference MDN JavaScript Looping code
Q111. Which snippet could you add to this code to print "YOU GOT THIS" to the
console?
let cipherText = [...'YZOGUT QGMORTZ MTRHTILS'];
let plainText = '';
/* Missing Snippet */
A
for (let key of cipherText.keys()) {
plainText += key % 2 === 0 ? key : ' ';
}
B
for (let [index, value] of cipherText.entries()) {
plainText += index % 2 !== 0 ? value : '';
}
C
for (let [index, value] of cipherText.entries()) {
plainText += index % 2 === 0 ? value : '';
}
D
for (let value of cipherText) {
plainText += value;
}
Charmander
Jigglypuff
Snorlax
Squirtle
Explanation: The pop() method removes the last element from an array and
returns that element. This method changes the length of the array.
Reference Array.pop
Q113. Which statement can be used to select the element from the DOM
containing the text "The LinkedIn Learning library has great JavaScript courses"
from this markup?
<h1 class="content">LinkedIn Learning</h1>
<div class="content">
<span class="content">The LinkedIn Learning library has great JavaScript
</div>
document.querySelector("div.content")
document.querySelector("span.content")
document.querySelector(".content")
document.querySelector("div.span")
Q114. Which value is not falsey?
[]
undefined
0
null
Reference Falsy
Q115. What line of code causes this code segment to throw an error?
const lion = 1;
let tiger = 2;
var bear;
++lion;
bear += lion + tiger;
tiger++;
line 5, because the prefix (++) operator does not exist in JavaScript
1. Reference const in js
2. Reference TypeError: invalid assignment to const "x"
Q116. What will be the value of result after running this code?
const person = { name: 'Dave', age: 40, hairColor: 'blue' };
const result = Object.keys(person).map((x) => x.toUpperCase());
1. Reference Object.keys()
2. Reference Array.prototype.map()
3. Reference String.prototype.toUpperCase()
Q117. Which snippet could you insert to this code to print "swim" to the console?
let animals = ["eagle", "osprey", "salmon"];
let key = animal => animal === "salmon";
animals.every(key)
animals.some(key).length === 1
animals.some(key)
Reference Array.prototype.some
Q118. What is the output of this code?
class RainForest {
static minimumRainFall = 60;
}
undefined
60
80
obj?.a.b
obj.a?.b
obj[a][b]
obj.?a.?b
[1,2,5,7]
[2,7]
[2,1,7,5]
a != b
a === b
Reference
Q123. What will this code log to the console?
console.log(typeof 41.1);
decimal
float
number
Reference
Q124. What is the output of this code?
let scores = [];
scores.push(1, 2);
scores.pop();
scores.push(3, 4);
scores.pop();
score = scores.reduce((a, b) => a + b);
console.log(score);
1. Reference Array.prototype.push()
2. Reference Array.prototype.pop()
3. Reference Array.prototype.reduce()
Q125. What does this code print to the console?
let bear = {
sound: 'roar',
roar() {
console.log(this.sound);
},
};
bear.sound = 'grunt';
let bearSound = bear.roar;
bearSound();
grunt
undefined
roar
Reference
Q126. What is the output of this code?
var cat = { name: 'Athena' };
function swap(feline) {
feline.name = 'Wild';
feline = { name: 'Tabby' };
}
swap(cat);
console.log(cat.name);
undefined
Wild
Tabby
Athena
Q127. What will this code output to the log?
var thing;
let func = (str = 'no arg') => {
console.log(str);
};
func(thing);
func(null);
null no arg
no arg no arg
null null
no arg null
Q128. What will this code print to the console?
const myFunc = () => {
const a = 2;
return () => console.log('a is ' + a);
};
const a = 1;
const test = myFunc();
test();
a is 1
a is undefined
It won't print anything.
a is 2
Q129. What will this code print to the console?
const myFunc = (num1, num2 = 2, num3 = 2) => {
return num1 + num2 + num3;
};
let values = [1, 5];
const test = myFunc(2, ...values);
console.log(test);
8
6
2
12
Q130. Which code would you use to access the Irish flag?
var flagsJSON =
'{ "countries" : [' +
🇮🇪
'{ "country":"Ireland" , "flag":" " },' +
🇷🇸
'{ "country":"Serbia" , "flag":" " },' +
🇵🇪
'{ "country":"Peru" , "flag":" " } ]}';
flagDatabase.countries[1].flag
flagDatabase.countries[0].flag
flagDatabase[1].flag
flagsJSON.countries[0].flag
Q131. Which snippet allows the acresOfRainForest variable to increase?
let conservation = true;
let deforestation = false;
let acresOfRainForest = 100;
if (/* Snipped goes here */){
++acresOfRainForest;
}
console.log(copyCat.type, copyCat.size);
tiger large
lion undefined
undefined large
lion large
Reference
Q135. What does this code print to the console?
let animals = [{ type: 'lion' }, 'tiger'];
let clones = animals.slice();
clones[0].type = 'bear';
clones[1] = 'sheep';
console.log(animals[0].type, clones[0].type);
console.log(animals[1], clones[1]);
18
10
9
20
Q137. Which snippet could you add to this code to print "{"type": "tiger"}" to the
console?
let cat = { type: "tiger", size: "large" };
cat.toJSON("type");
JSON.stringify(cat, ["type"]);
JSON.stringify(cat);
JSON.stringify(cat, /type/);
Reference
Q138. Which document method is not used to get a reference to a DOM node?
document.getNode();
document.getElementsByClassName();
document.querySelectorAll();
document.querySelector();
Reference
Q139. In JavaScript, all objects inherit a built-in property from a ****___****.
node
instance variable
prototype
accessor
Reference
Q140. Which of the following are not server-side Javascript objects?
Date
FileUpload
Function
All of the above
Q141. What will be the output of the following code snippet?
const obj1 = { first: 20, second: 30, first: 50 };
console.log(obj1);
first: 30 , second: 50
first: 50 , second: 30
first: 30 , second: 20
None of the above
Q142. Which object in Javascript doesn’t have a prototype?
Base Object
All objects have prototype
None of the objects have prototype
None of the above
Q143. What does … operator do in JS?
Used to spread iterables to individual elements
Describe datatype of undefined
No such operator exists
None of the above
Q144. How to stop an interval timer in Javascript?
clearInterval
clearTimer
intervalOver
None of the above
Reference
Q145. What will be the output of the following code snippet?
print(typeof NaN);
Object
Number
String
None of the above
Q146. What will be the output of the following code snippet?
<script type="text/javascript">a = 5 + "9"; document.write(a);</script>
Compilation Error
14
Runtime Error
59
Q147. Which of the following methods can be used to display data in some form
using Javascript?
document.write()
console.log()
window.alert()
all of the above
Q148. What value is assigned to total after this code executes?
function sum(num1, num2 = 2, num3 = 3) {
return num1 + num2 + num3;
}
let values = [1, 5];
let total = sum(4, ...values);
10
6
7
8
Reference: Rest parameters
Q149. Which statement is applicable to the defer attribute of the HTML <script>
tag?
defer allows the browser to continue processing the page while the script loads in
the background.
defer causes the script to be loaded from the backup content delivery network
(CDN).
defer blocks the browser from processing HTML below the tag until the script is
completely loaded.
defer lazy loads the script, causing it to download only when it is called by
another script on the page.
Reference: defer html script attribute
Q150. Which method of a class is called to initialize an object of that class?
init()
create()
new()
constructor()
Reference: constructor method
Q151. Which expression evaluates to true?
Boolean(NaN)
Boolean(0)
Boolean("false")
Boolean("")
Reference: Boolean object
Q152. How would you check if the word "pot" is in the word "potato"?
"pot".indexOf("potato") !== -1
"potato".includes("Pot")
"potato".includes("pot")
"potato".contains("pot");
Reference: String.prototype.includes()
Q153. Which collection object allows a unique value to be inserted only once?
Map
Array
Set
Object
Reference: developer.mozilla Set
Q154. How would you change the color of this header to pink?
<h2 id="cleverest">girls</h2>
document.getElementByName("cleverest").style.color = "pink";
document.getElementsByTagName("h2").style.color = "pink";
document.getElementByName("h2").style.color = "pink";
document.getElementById("cleverest").style.color = "pink";
Reference: W3Schools HTML DOM Style color Property
Q155. Which line is missing from this code if you expect the code to evaluate to
true?
var compare = function(test1, test2) {
// Missing line
}
test1==test2;
return test1===test2;
return test1==test2;
return test1!=test2;
Reference: MDN Equality Docs