Modifying an array

When I try to modify the array below and log the result, what it shows is the original array and not the string! The string will be shown only if I assign a variable to the output or console.log(numbers.join(’ , ') directly?

let numbers = [1, 2, 3];

numbers.join(',');

console.log(numbers);

and when I use the .sort method it worked.


const numbers = [2, 3, 1]

numbers.sort();
console.log(numbers);

so what is the criteria?

The criteria is:
You need to know how the function you are using will behave. It either returns the value or doesn’t return any value (in this case, it will perform the operation directly on the passed value (object/string/…).

.join() returns the modified data.
So, you need to assign the returning value to some variable or you won’t be able to see the change.

.sort() doesn’t return anything. It just does it’s thing and after calling this method on any data, you can see the effect if you console log that data after the function call.

FYI: just look for those methods in google (JavaScript | MDN) and you will find a detailed description for the method.

Good luck

You’re saying that .join() returns the modified data meaning it will modified the array into a string, while .sort() won’t modified it?

when you use .join() method, you are expected to save the returned output like:

let result = numbers.join(',');
// then probably do something with the output.
console.log(result)

while .sort() will modify the data you are passing to the method directly without having to save it in any variable like above.
so,

let numbers = [3, 1, 10, 4, 7];
numbers.sort(); // notice that I haven't saved the result in any variable here.
console.log(numbers);
// expected output: [1, 3, 4, 7, 10]
// but it won't sort number as above.
// this is funnier part of JavaScript. sort() will treat those as strings and then do the comparison. 

// to sort numbers:
numbers.sort( (a, b) => a-b );

Is that clear?

for me both methods would modified the data, join() and sort() would both modified it somehow.
Anyways…

let numbers = [3, 1, 10, 4, 7];
//because you add 10, it will come second in the output...very weird...and thanks for the sort numbers code.

JavaScript is weird but if you use best practices and test your code, you can expect good results.

Happy to help and happy coding.

1 Like