Feature Image

Today we are going to continue learning our beloved JavaScript language, in this edition, we are going to test our skills by answering some JavaScript mini-challenges.

Even though I’ll be giving the answer with an explanation at the end of each question, try to figure it out by yourself first, and then validate your answer against mine.

Question #1: Array Sort Comparison

Consider the following arrays and conditions, what do you think would be the result?

const arr1 = ['a', 'b', 'c']
const arr2 = ['c', 'b', 'a']

console.log(
    arr1.sort() === arr1,
    arr2 === arr2.sort(),
    arr1.sort() === arr2.sort()
)

Answer

true true false

Now that we know the result, let’s explain why. For the first 2 outputs the explanation is rather simple, the sort() method sorts the original array and returns a reference to the same object, so arr1.sort() is actually a reference to the same object as arr1.

For the third output, arr1.sort() === arr2.sort(), even though the elements on each one of the arrays are the same, the === operator will not test the elements of the array but the reference of each object, which in this case is different, and thus returning false.

If you want to know more about array comparisons, check my article Stranger Things, JavaScript Edition, and read Scenario #5: Array equality where I explain with more samples some weird array comparisons with explanations.


Question #2: Object Mutability

For this scenario, I’d like to simulate an object which represents an author, and information about his website. We will then use the method Object.freeze() so it can’t be changed, and we will put it to the test. What do you think will be the result?

const author = {
  name: 'Juan',
  website: {
    type: 'blog',
    url: 'https://livecodestream.dev',
  }
}

Object.freeze(author)

author.website.type = 'test'

console.log(author.website.type)

#javascript #questions #programming

5 JavaScript Questions and Answers to Test Your Skills
1.45 GEEK