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);

courses.sort();
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 = a.name.toUpperCase(); // if toLowerCase be sure are in both
// const nameB = b.name.toUpperCase();

// 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) => a.id - b.id);
const coursesSortedAlphabetically = […courses].sort((a, b) =>a.name.localeCompare(b.name));

console.log(courses);
console.log(coursesSortedByNumber);
console.log(coursesSortedAlphabetically);

[…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