-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?

9
  • 2
    In second example do a = a.join() Commented Jun 1, 2017 at 12:14
  • join() doesn't modify the original value. Commented Jun 1, 2017 at 12:15
  • see stackoverflow.com/questions/9009879/… Commented Jun 1, 2017 at 12:15
  • @Pyromonk that's my question. do i need to learn each individual method to see if it alters the original or not? Commented Jun 1, 2017 at 12:16
  • 1
    @Theworm2 Only arrays and objects can be mutated. So any function that returns some other type can't possibly alter the original to do it. Commented Jun 1, 2017 at 12:18

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.