JS Tutorials
JS Objects
JS Functions
JS Classes
JS Aysnc
The JavaScript method toString()
converts an array to a
string of (comma separated) array values.
const fruits =
["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
The join()
method also joins all array elements into a
string.
It behaves just like toString()
, but in addition you can
specify the separator:
const fruits =
["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:
When you work with arrays, it is easy to remove elements and add new elements.
This is what popping and pushing is:
Popping items out of an array, or pushing items into an array.
The pop()
method removes the last element from an array:
const fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes "Mango" from fruits
The pop()
method returns the value that was "popped out":
const fruits =
["Banana", "Orange", "Apple", "Mango"];
let x =
fruits.pop(); // x = "Mango"
The push()
method adds a new element to an array (at the
end):
const fruits =
["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds "Kiwi" to fruits