5.4 Adding To Arrays
JS arrays allow you to directly add to an array without using another type of data structure.
In Java, you would need an
ArrayList
. In C++, you would need a vector
.You can add to an Array with the use of the
.push()
, .unshift()
, or .concat()
methods..push()
Example
let fruits = ['apple', 'banana', 'grapes']; fruits.push('dragon fruit', 'pear'); // fruits = ['apple', 'banana', 'grapes', 'dragon fruit', 'pear'];
Here we see that the
.push()
adds to the end of the array the new item I put into the method parameter. You could add as many new items as you want..unshift()
Example
let fruits = ['apple', 'banana', 'grapes']; fruits.unshift('dragon fruit', 'pear'); // fruits = ['dragon fruit', 'pear', 'apple', 'banana', 'grapes'];
Here we see that the .unshift() adds to the beginning of the array the new item I put into the method parameter. You can add as many new items as you want.
.concat()
Example
let fruits = ['apple', 'banana', 'grapes']; fruits.concat(['dragon fruit', 'pear']); // fruits = ['apple', 'banana', 'grapes', 'dragon fruit', 'pear'];
Here we see that the
.concat()
takes an array as a parameter and adds the new items into the array.The two methods did the exact same thing, so which one is better?
Both are perfectly valid. The only reason you MAY use one over the other is the number of entries you want to add to the array.
If there are multiple entries that I want to add I would use
.concat()
. If it’s just a single entry, then I would use
.push()
. However, you can accomplish the same goal using either.
Previous Section
5.3 Iterating Through ArraysNext Section
5.5 Objects v. ArraysCopyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.