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