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];
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.
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.
while .sort() will modify the data you are passing to the method directly without having to save it in any variable like above.
let numbers = [3, 1, 10, 4, 7];
numbers.sort(); // notice that I haven't saved the result in any variable here.
// expected output: [1, 3, 4, 7, 10]
// but it won't sort number as above.
// to sort numbers:
numbers.sort( (a, b) => a-b );