## DEV Community

Nick Scialli (he/him)

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

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.

# 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()
);
``````

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: `[{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);
``````

`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());
``````

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: `["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));
``````

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!

Let's display some notifications to our user! What gets logged in the following snippet?

``````const notifications = 1;

console.log(
1 && 's'}`
);
``````

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: `[{ 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));
``````

`['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]);
``````

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!

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

HaiDV • Edited

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

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

HaiDV

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

Thank you for the reference. :)

Mark Magyarodi

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

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

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...

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

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!

Larry Saytee

Thanks.

Habdul Hazeez

This repo comes to mind:

# 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! ๐

See 17 Available Translations ๐ช๐ธ๐ฎ๐น๐ฉ๐ช ๐ซ๐ท๐ท๐บ๐จ๐ณ๐ต๐น

###### 1. What's the output?
```function sayHi() {
console.log(name);
console.log(age```
โฆ

Nick Scialli (he/him)

Thanks! This looks like a great reference.

Mehedi Hasan Likhon

Thank you!

Nick Scialli (he/him)

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

Abel Lifaefi Mbula

Nice and very beginner friendly.

beginner friendly

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

Jorge

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

Nick Scialli (he/him)

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

Henry Ohanga

Excellent work Nick!

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!

marjanb

Nice work, excellent examples!

Nick Scialli (he/him)

Thanks!

Ememobong-dev

i found this very helpful, i just began learning "Promise, Aysnc/Await" couldn't relate to the Promise question but i am 100% coming back to answer the quiz. Yup!! I love i saw this article. Thanks

Praveen Saraogi

Damn this proves, I've lot to learn about JS even after completing advance JS course from udemy.

Nick Scialli (he/him)

Like any other language, JS has its fair share of idiosyncrasies. We all have more to learn!