Does .join method change the array into string in Javascript?

2.5k views Asked by At

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

There are 3 answers

0
SzybkiSasza On BEST ANSWER

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

0
dsharew On

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.

0
Rana On

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"