1

The result for .join is different from .push or .pop.

var mack=[];

mack.push("dog", "cat");
mack.join(" ");

alert(mack);

Console.log: ["dog", "cat"]


var mack=[];

mack.push("dog", "cat");

alert(mack.join(" "));

Console.log: "dog cat"


In the first one, mack.join(" "); does not change the original mack array, unlike mack.push("dog", "cat"); or mack.pop();.

I'm curious that why this happened. And is there any other method like this?

3 Answers 3

3

The join() function doesn't change the element of array that's only represent the array elements as string with the separator what we give as argument. here is the reference of join function Array.prototype.join()

Array push and pop is use to add or remove element from a array that return array new size for push and element for POP.

Array.prototype.push()

Array.prototype.pop()

Here the array elements are ok as you pushed on it.

var mack=[];

    mack.push("dog", "cat");

var mack_string = mack.join(" ");

console.log(mack); // Array [ "dog", "cat" ]

console.log(mack_string); // "dog cat"

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

Comments

2

Push and pop methods are used on Array object to add or remove data to/from Array and therefore change Array itself.

Join method doesn't change Array, it returns String - new object, Array remains unchanged as it is. It could be used e.g. for concatenating Strings which are put in array with particular character.

More about arrays could be found here: http://www.w3schools.com/js/js_array_methods.asp

Comments

1

The join() method joins all elements of an array into a string, detail

It returns a string and does not modify the original array.
Also it does not make sense to assign String for Array object, if that was your expectation.

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.