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!
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: 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
.
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.
#javascript #questions #programming