DEV Community

Cover image for JavaScript Quiz Question #1: Array Sort Comparison
Nick Scialli (he/him)
Nick Scialli (he/him)

Posted on

JavaScript Quiz 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

A) true true true
B) true true false
C) false false false
D) true false true

Put your answer in the comments!

Top comments (19)

Collapse
 
quoll profile image
Paula Gearon

The question, as asked, is misleading. Arrays don't compare in Javascript! 🙂 Also, while the arr1 and arr2 values don't change, the arrays they refer to do, so the const is likely to trip some people up.

The .sort function returns the array that was sorted, so comparing arr1.sort() to arr1 is just comparing the array reference to itself. The same goes for arr2 on the next line (the use of == is another potential red herring, since the arrays are the same, so type conversion doesn't happen). Finally, while the sorted arrays contain the same info, arr1 is a different object to arr2, so the final comparison is false.

B

Collapse
 
nas5w profile image
Nick Scialli (he/him)

Which part of the question is misleading? Can you quote it here so I can fix it?

Collapse
 
quoll profile image
Paula Gearon

Sorry... my wording was probably unclear. I mean that it's a trick question. It has red herrings in it.

The misleading nature is where you state: "...in various sorting conditions?"
This misleads the reader since sorting is irrelevant here. The only real relevance is that the sort() method returns the original array object.

Collapse
 
yogeshmedz profile image
YogeshMedz

B). true true false
Because === is used for comparison between two variables but this will check strict type, which means it will check datatype and compare two values and == is used for comparison between two variables irrespective of the datatype of variable.

Collapse
 
hongquangraem profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
hongquangraem

c

Collapse
 
yavuztor profile image
Yavuz Tor

B

Collapse
 
javaarchive profile image
Raymond

D?

Collapse
 
andrewslobodianiuk profile image
Andrew Slobodianiuk

B

Collapse
 
ivanesko69 profile image
Ivo

D

Collapse
 
vladdekhanov profile image
Dekhanov Vladislav

I guess the correct answer is B

Collapse
 
avxkim profile image
Alexander Kim

B

Collapse
 
vanbui1995 profile image
vanbui1995

B

Collapse
 
hafizsohail_ahmed_2b61ad profile image
Hafiz Sohail Ahmed

D

Some comments may only be visible to logged-in visitors. Sign in to view all comments.