DEV Community

Cover image for 10 JavaScript Quiz Questions and Answers to Sharpen Your Skills
Nick Scialli (he/him)
Nick Scialli (he/him)

Posted on • Updated on • Originally published at typeofnan.dev

10 JavaScript Quiz Questions and Answers to Sharpen Your Skills

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!

Let me know in the comments if you learn anything from the quiz!


Edit: The second edition of quiz questions is now up! Check it out here.


If you enjoy this quiz, please give it a 💓, 🦄, or 🔖 and consider:


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()
);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.


If you enjoy this quiz, please give it a 💓, 🦄, or 🔖 and consider:


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());
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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'}`
);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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]);
Enter fullscreen mode Exit fullscreen mode

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.


The second edition of quiz questions is now up! Check it out here.


If you enjoy this quiz, please give it a 💓, 🦄, or 🔖 and consider:


Want more quiz questions? Head over to https://quiz.typeofnan.dev for 62 additional JavaScript quiz questions!

Top comments (28)

Collapse
 
salyadav profile image
Saloni Yadav

Well picked examples. I got something similar to question 8 in one of the js interviews. Also, could you explain question 5 a little more in terms of the event loop? Why promise.all returns in the same order... wouldn’t the event loop resolve based on the settimeout delay once the promise is returned? Thanks

Collapse
 
haidv profile image
HaiDV • Edited

Promise.all waits all promised to be resolved. That 's the simplest explanation

Collapse
 
salyadav profile image
Saloni Yadav

Yes. But my question is regarding the order of printing.

Thread Thread
 
haidv profile image
HaiDV

It also ensure the order of data from promises. More info here: developer.mozilla.org/en/docs/Web/...

Thread Thread
 
salyadav profile image
Saloni Yadav

Thank you for the reference. :)

Thread Thread
 
ribizlim profile image
Mark Magyarodi

the console.log is done only once after all promises are resolved, not for each timeout

Thread Thread
 
salyadav profile image
Saloni Yadav

Will not the print be in the order of resolution even if they are all printed after all the promises are resolved?

Thread Thread
 
ribizlim profile image
Mark Magyarodi

No, Promise.all takes an array off promisses and resolves to an array of all promise results in the same order. The array is what will be printed...

Thread Thread
 
salyadav profile image
Saloni Yadav

Okay!! this is the exact clarification I was looking for! Thank you! :)

Collapse
 
hiboabd profile image
Hibo Abdilaahi

Such a coincidence that I stumbled across the fact that comparing arrays that are exactly the same as each other in appearance (e.g. ([] === [])) would yield a false boolean result. So I'm glad to get an explanation for that! And it was a much simpler explanation than I thought haha.

Really great article thanks!

Collapse
 
webmediacre profile image
Larry Saytee

Thanks.

Collapse
 
ziizium profile image
Habdul Hazeez

This repo comes to mind:

GitHub logo lydiahallie / javascript-questions

A long list of (advanced) JavaScript questions, and their explanations ✨

JavaScript Questions


I post multiple choice JavaScript questions on my Instagram stories, which I'll also post here! Last updated: December 24th

From basic to advanced: test how well you know JavaScript, refresh your knowledge a bit, or prepare for your coding interview! 💪 🚀 I update this repo regularly with new questions. I added the answers in the collapsed sections below the questions, simply click on them to expand it. It's just for fun, good luck! ❤️

Feel free to reach out to me! 😊
Instagram || Twitter || LinkedIn || Blog


See 17 Available Translations 🇪🇸🇮🇹🇩🇪 🇫🇷🇷🇺🇨🇳🇵🇹


1. What's the output?
function sayHi() {
  console.log(name);
  console.log(age
Collapse
 
nas5w profile image
Nick Scialli (he/him)

Thanks! This looks like a great reference.

Collapse
 
devlikhon profile image
Mehedi Hasan Likhon

Thank you!

Collapse
 
nas5w profile image
Nick Scialli (he/him)

You're welcome! I'll try to do some more next week

Collapse
 
bam92 profile image
Abel Lifaefi Mbula

Nice and very beginner friendly.

Collapse
 
ar7max profile image
Maxim • Edited

Answers to Sharpen Your Skills
beginner friendly

and this is what makes me cringe, cause fundamentals are fundamentals

Collapse
 
jfosela81 profile image
Jorge

You have a new susbcriber! Thanks for the quiz! I have learnt a little bit more of JS!

Collapse
 
nas5w profile image
Nick Scialli (he/him)

Wonderful! I hope to put out another version next week with more questions and aswers

Collapse
 
henryohanga profile image
Henry Ohanga

Excellent work Nick!

Collapse
 
codebeeme profile image
Cătălin Anghel-Ursu

Time for some mind food, and your JS quiz list was a tasty treat! You got a new follower.
Thanks for the nice work, Nick!

Collapse
 
shafkathullah profile image
Shafkathullah Ihsan

Cool!