What does the `sort()` method do in JavaScript?
A
Sorts numbers in descending order by default
B
Sorts the array alphabetically by default
C
Removes duplicates from the array
D
Creates a new sorted array without modifying the original
Analysis & Theory
`sort()` by default sorts elements as strings in alphabetical order.
What is the result of `[40, 100, 1, 5, 25, 10].sort()`?
A
[1, 5, 10, 25, 40, 100]
B
[100, 10, 1, 25, 40, 5]
C
[1, 10, 100, 25, 40, 5]
D
[5, 1, 10, 25, 40, 100]
Analysis & Theory
`sort()` converts numbers to strings, so it sorts based on string Unicode values.
How can you sort numbers in ascending order using `sort()`?
B
arr.sort((a, b) => a - b)
C
arr.sort((a, b) => b - a)
Analysis & Theory
Use a custom compare function: `(a, b) => a - b` for ascending numeric sort.
How do you sort numbers in descending order?
B
arr.sort((a, b) => a + b)
C
arr.sort((a, b) => b - a)
D
arr.sort((a, b) => b * a)
Analysis & Theory
`(a, b) => b - a` sorts numbers from highest to lowest.
What does the `reverse()` method do?
A
Sorts numbers in descending order
B
Reverses the original array in place
C
Creates a reversed copy
Analysis & Theory
`reverse()` reverses the order of elements in the same array.
Which of the following sorts strings alphabetically?
Analysis & Theory
`sort()` without arguments sorts strings in alphabetical order.
How do you sort an array of strings in **reverse alphabetical order**?
C
arr.sort((a, b) => a + b)
Analysis & Theory
First sort alphabetically, then reverse the result: `arr.sort().reverse()`.
What happens if `sort()` is called on an array of mixed numbers and strings?
B
It sorts numbers then strings
C
It converts all elements to strings and sorts alphabetically
Analysis & Theory
`sort()` converts all items to strings and sorts them alphabetically.
Can you sort an array of objects using `sort()`?
A
Yes, with a custom compare function
B
No, objects can't be sorted
C
Only if all properties are numbers
D
Only strings can be sorted
Analysis & Theory
Use a compare function like `(a, b) => a.age - b.age` to sort objects by property.
Which of these correctly sorts an array `arr` from highest to lowest?
A
arr.sort((a, b) => a - b)
B
arr.sort((a, b) => b - a)
Analysis & Theory
Both `sort((a, b) => b - a)` and `sort().reverse()` will sort descending (if all elements are sortable as strings or numbers).