- Concatenation means to join items end to end. JavaScript offers the
concat
method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument toconcat
, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays. - Here's an example:
[10, 20, 30].concat([40, 50, 60]);
The returned array would be
[10, 20, 30, 40, 50, 60]
.Now let's use the
concat
method in thenonMutatingConcat
function to concatenateattach
to the end ofbegin
. The function should return the concatenated array.
function nonMutatingConcat(original, attach) {
// Only change code below this line
// Only change code above this line
}
var first = [1, 2, 3];
var second = [4, 5];
nonMutatingConcat(first, second);
- Answer:
function nonMutatingConcat(original, attach) {
return original.concat(attach)
}
var first = [1, 2, 3];
var second = [4, 5];
console.log(nonMutatingConcat(first, second)); // willreturn [1, 2, 3, 4, 5]
Larson, Quincy, editor. “Combine Two Arrays Using the concat Method.” Https://Www.freecodecamp.org/, Class Central, 2014, twitter.com/ossia.
Top comments (0)