An array's length, like the data types it can contain, is not fixed. Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are mutable. In this challenge, we will look at two methods with which we can programmatically modify an array:
Array.push()
andArray.unshift()
.Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the
push()
method adds elements to the end of an arrayThe
unshift()
adds elements to the beginning. Consider the following:
function mixedNumbers(arr) {
let begArray = arr.unshift("I", 2, "three");
let endArray = arr.push(7, "VIII", 9);
return arr;
}
console.log(mixedNumbers(['IV', 5, 'six'])); console will display
["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]
- Here We have defined a function,
mixedNumbers
, which we are passing an array as an argument. We modified the function by usingpush()
andunshift()
to add'I', 2, 'three'
to the beginning of the array and7, 'VIII', 9
to the end so that the returned array contains representations of the numbers 1-9 in order.
Top comments (0)