10 JavaScript Quiz Questions and Answers to Sharpen Your Skills
Nick Scialli
May 27, 2020
One way we can challenge ourselves to grow as JavaScript developers is to practice with quiz questions! The following questions are intended to be challenging and instructive. If you know exactly how to answer each one, that’s great, but if you get some wrong and learn why you got it wrong, I contend that’s even better!
Question 1: Array Sort Comparison
Consider the following arrays. What gets logged in various sorting conditions?
const arr1 = ['a', 'b', 'c'];
const arr2 = ['b', 'c', 'a'];
console.log(
arr1.sort() === arr1,
arr2.sort() == arr2,
arr1.sort() === arr2.sort()
);
Answer and Explanation
Answer: true, true, false
There are a couple concepts at play here. First, the array sort
method sorts your original array and also returns a reference to that array. This means that when you write arr2.sort()
, the arr2
array object is sorted.
It turns out, however, the sort order of the array doesn’t matter when you’re comparing objects. Since arr1.sort()
and arr1
point to the same object in memory, the first equality test returns true
. This holds true for the second comparison as well: arr2.sort()
and arr2
point to the same object in memory.
In the third test, the sort order of arr1.sort()
and arr2.sort()
are the same; however, they still point to different objects in memory. Therefore, the third test evaluates to false
.
Question 2: A Set of Objects
Consider the following Set
of objects spread into a new array. What gets logged?
const mySet = new Set([{ a: 1 }, { a: 1 }]);
const result = [...mySet];
console.log(result);
Answer and Explanation
Answer: [{a: 1}, {a: 1}]
While it’s true a Set
object will remove duplicates, the two values we create our Set
with are references to different objects in memory, despite having identical key-value pairs. This is the same reason { a: 1 } === { a: 1 }
is false
.
It should be noted if the set was created using an object variable, say obj = { a: 1 }
, new Set([ obj, obj ])
would have only one element, since both elements in the array reference the same object in memory.
Question 3: Deep Object Mutability
Consider the following object representing a user, Joe, and his dog, Buttercup. We use Object.freeze
to preserve our object and then attempt to mutate Buttercup’s name. What gets logged?
const user = {
name: 'Joe',
age: 25,
pet: {
type: 'dog',
name: 'Buttercup',
},
};
Object.freeze(user);
user.pet.name = 'Daffodil';
console.log(user.pet.name);
Answer and Explanation
Answer: Daffodil
Object.freeze
will perform a shallow freeze on an object, but will not protect deep properties from being mutated. In this example, we would not be able to mutate user.age
, but we have no problem mutating user.pet.name
. If we feel we need to protect an object from being mutated “all the way down,” we could recursively apply Object.freeze
or use an existing “deep freeze” library.
Question 4: Prototypal Inheritance
In this question, we have a Dog
constructor function. Our dog obviously knows the speak command. What gets logged in the following example when we ask Pogo to speak?
function Dog(name) {
this.name = name;
this.speak = function () {
return 'woof';
};
}
const dog = new Dog('Pogo');
Dog.prototype.speak = function () {
return 'arf';
};
console.log(dog.speak());
Answer and Explanation
Answer: woof
Every time we create a new Dog
instance, we set the speak
property of that instance to be a function returning the string woof
. Since this is being set every time we create a new Dog
instance, the interpreter never has to look farther up the prototype chain to find a speak
property. As a result, the speak
method on Dog.prototype.speak
never gets used.
Question 5: Promise.all Resolve Order
In this question, we have a timer
function that returns a Promise
that resolves after a random amount of time. We use Promise.all
to resolve an array of timers
. What gets logged, or is it random?
const timer = (a) => {
return new Promise((res) =>
setTimeout(() => {
res(a);
}, Math.random() * 100)
);
};
const all = Promise.all([timer('first'), timer('second')]).then((data) =>
console.log(data)
);
Answer and Explanation
Answer: ["first", "second"]
The order in which the Promises resolve does not matter to Promise.all
. We can reliably count on them to be returned in the same order in which they were provided in the array argument.
Question 6: Reduce Math
Math time! What gets logged?
const arr = [(x) => x * 1, (x) => x * 2, (x) => x * 3, (x) => x * 4];
console.log(arr.reduce((agg, el) => agg + el(agg), 1));
Answer and Explanation
Answer: 120
With Array#reduce
, the initial value of the aggregator (here, named agg
) is given in the second argument. In this case, that’s 1
. We can then iterate over our functions as follows:
1 + 1 * 1 = 2 (value of aggregator in next iteration)
2 + 2 * 2 = 6 (value of aggregator in next iteration)
6 + 6 * 3 = 24 (value of aggregator in next iteration)
24 + 24 * 4 = 120 (final value)
So, 120 it is!
Question 7: Short-Circuit Notification(s)
Let’s display some notifications to our user! What gets logged in the following snippet?
const notifications = 1;
console.log(
`You have ${notifications} notification${notifications !== 1 && 's'}`
);
Answer and Explanation
Answer: “You have 1 notificationfalse”
Unfortunately, our short-circuit evaluation will not work as intended here: notifications !== 1 && 's'
evaluates to false
, meaning we will actually be logging You have 1 notificationfalse
. If we want our snippet to work correctly, we could consider the conditional operator: ${notifications === 1 ? '' : 's'}
.
Question 8: Spread and Rename
Consider the following array with a single object. What happens when we spread that array and change the firstName
property on the 0-index object?
const arr1 = [{ firstName: 'James' }];
const arr2 = [...arr1];
arr2[0].firstName = 'Jonah';
console.log(arr1);
Answer and Explanation
Answer: [{ firstName: "Jonah" }]
Spread creates a shallow copy of the array, meaning the object contained in arr2
is still pointing to the same object in memory that the arr1
object is pointing to. So, changing the firstName
property of the object in one array will be reflected by the object in the other array changing as well.
Question 9: Array Method Binding
What gets logged in the following scenario?
const map = ['a', 'b', 'c'].map.bind([1, 2, 3]);
map((el) => console.log(el));
Answer and Explanation
Answer: 1 2 3
['a', 'b', 'c'].map
, when called, will call Array.prototype.map
with a this
value of ['a', 'b', 'c']
. But, when used as a reference, rather than called, ['a', 'b', 'c'].map
is simply a reference to Array.prototype.map
.
Function.prototype.bind
will bind the this
of the function to the first parameter (in this case, that’s [1, 2, 3]
), and invoking Array.prototype.map
with such a this
results in those items being iterated over and logged.
Question 10: Set Uniqueness and Ordering
In the following problem, we use the Set
object and spread syntax to create a new array. What gets logged (to consider: Are items forced to be unique? Are they sorted?)
const arr = [...new Set([3, 1, 2, 3, 4])];
console.log(arr.length, arr[2]);
Answer and Explanation
Answer: 4 2
The Set
object will force unique elements (duplicate elements already in the set are ignored), but will not change order. The resultant arr
array will be [3, 1, 2, 4]
, meaning arr.length
is 4
and arr[2]
(the third element of the array) is 2
.
Nick Scialli is a senior UI engineer at Microsoft.