Somebody tell me why these arrays appear all sorted

I am doing exercises por the Ultimate JavaScrip course Part 1 - Fundamentals, in Section 6- Arrays, Lesson 12- Sorting Arrays. Please tell me why, when I comment the statements that use the courses.sort(function(a, b)… the array courses appear unsorted, but when I un-comment them, the arrays (logged to console at different times ) appear all sorted :

Please run this code as is, and look at the console. Then un-comment the last part that use the “sort(function)” and run it again and you will see. Here is the code:

// When sorting arrays with objects, there is extra work to do:

const courses = [
{ id:3, name: ‘Node.js’},
{ id:1, name: ‘JavaScript’},
{ id:2, name: ‘HTML5’},
{ id:4, name: ‘CSS3’} // we want to sort based in the name
console.log('Original: ', courses);

console.log('with sort: ', courses); // Nothig happens, so…

// courses.sort(function(a, b) {
// // a < b => -1
// // a > b => 1
// // a === b => 0;
// // toUpperCase or toLowerCase to avoid missorting by lower/upper casing

// const nameA =; // if toLowerCase be sure are in both
// const nameB =;

// if (nameA < nameB) return -1;
// if (nameA > nameB) return 1;
// return 0;
// });
// console.log('with function: ', courses);

//////// I don´t know why, but executing the sort(function),
//////// courses appear sorted from the beggining!!!

Unlike other array functions sort() does not return a new array with the result but operates in place on the array it is called on.

Thanks for your comment @SAM

Hi Ricardo,

this is my CheatSheet for sorting adapted to your courses example:

const coursesSortedByNumber = […courses].sort((a, b) => -;
const coursesSortedAlphabetically = […courses].sort((a, b) =>;


[…courses] makes a copy of the original courses array (see SAMs comment)

if you use localeCompare() it does’t matter if the names are upper or lowerCase

Thanks for your advise @Birgit