More Arrays

Elements can be added to arrays with the push method.

var dorks = ["me", "einstein"];
dorks.push("you");
console.log(dorks); // ["me", "einstein", "you"]

Welcome to the dork club!

Multiple elements can be added to an array with the push method.

var n = [1, 2];
n.push(3, 4);
console.log(n); // [1, 2, 3, 4]

Array elements can be updated by indexing into the array and assigning the element to a new value.

var games = ["halo", "starcraft"];
games[0] = "candyland";
console.log(games); // ["candyland", "starcraft"]

The join method can be used to combine all the elements of an array into a single string.

var lol = ["i", "like", "ice", "cream"];
var lolString = lol.join(" ");
console.log(lolString); // "i like ice cream"
Question Click to View Answer

What does the following code print to the console?

var nums = [8, 1, 3];
nums.push(99);
console.log(nums);
[8, 1, 3, 99]

The push method can be used to add elements to the end of an array.

What does the following code print to the console?

var blah = [];
blah.push("bat", "fat");
console.log(blah);
["bat", "fat"]

The blah variable is initially assigned to the empty array. The push method is then used to add the "bat" and "fat" strings to the array.

What does the following code print to the console?

var liz = ["silly"];
liz.push("crazy", "funny");
console.log(liz.length);

3

The liz variable is initially assigned to an array with one element. Two additional elements are added to the liz array, so the length is 3.

What does the following code print to the console?

var rain = [];
rain.push("wet");
rain[0] = "fun";
console.log(rain);
["fun"]

The rain variable is initially assigned to the empty array. The "wet" string is then added to the rain array. The first element of the rain array ("wet") is then replaced with the string "fun". The rain array is then printed to the console.

What does the following code print to the console?

var awesome = ["programming", "is", "fun"];
console.log(awesome.join(" "));

programming is fun

The join() method concatenates all the elements of the array into a single string.

<-- Previous (While Loops With Arrays) Next (Introduction to Functions) -->