-1

Bit of a weird title, let me explain.

Take this:

let a = ['a', 'b', 'c']
function joining(){
    console.log(a.join())
}
joining() // a,b,c
THE ABOVE IS JOINED

function joining(){
    a.join()
    console.log(a)
}
joining() // ['a', 'b', 'c']
THE ABOVE IS NOT JOINED

function pushing(){
    a.push('d')
    console.log(a)
}
pushing() // ['a', 'b', 'c', 'd']
THE ABOVE IS PUSHED

The first joining() joins them correctly as I have called .join() on the array. However, the second one I have called joined on it and then tried to log it but it displays the original. However I did exactly the same with the push() method and that changed the original array. how can I tell what methods will change the original array and which wont or is it just a case of learning each method?

2 Answers2

2

The reason that a.join() does not output your expected result in the second instance is because you have not assigned the returned value from the invocation of the method.

a = a.join();
console.log(a);

For completeness, in your first example the expected output is logged on the console because the returned value from the invocation is passed as a parameter to console.log().

Scott
  • 1,863
  • 2
  • 24
  • 43
1

The join() method joins the elements of an array into a string, and returns the string.

Therefore, you should update it into:

a = a.join()
omri_saadon
  • 10,193
  • 7
  • 33
  • 58