How to create a function to take an array and append an element at the end.

How to create a function to take an array and append an element at the end.

In this post, we will create a function to take an array and element as an argument and return the array with the element at the end of the array.

Let's break this down into chunks...

  1. We need a function.
  2. An array and element are required to pass into the function.
  3. We must return the array.
  4. The element we pass into an array, must be at the end of the array.

First, We create our function and give the function a name. In our example, our function name is "append"

const append = () => {
"do something"
}

Second, An array and an element are required to pass into the function. we add two arguments array and element into our function

const append = (array, element) => {
"do something"
}

Third, We must return an array. which is the "do something"

const append = (array, element) => {
return array 
}

Fourth, The element must be at the end of the array. To add an element to an array we demonstrate the push() method. Again, this is to "do something".

Note: Javascript push() method by default we add an element at the end of an array.

const append = (array, element) => {
array.push(element) 
return array 
}

Using the push() method in this function is not ideal. it will modify data outside of the function

A better approach is to use a spread operator, it will not mutate the original array. The spread operator (...) allows us to copy all or part of an existing array to a new array.

In our example, we will use the spread operator followed by our two arguments [...array, element]

const append = (array, element) => {
return [...array, element];
};

To check our function, let's create an array named "fastCars" with 3 of my favourite car brands.

const fastCars = ["Porsche", "Mercedes-Benz", "Lamborghini"];

Next, we will declare a new array and pass our original array fastCars and our element "Ferrari" into our function.

const newCarBrand = append(fastCars, "Ferrari") ;

Your code should look like this.

const fastCars = ["Porsche", "Mercedes-Benz", "Lamborghini"];

const append = (array, element) => {
  return [...spread, element];
};

const newCarBrand = append(fastCars, "Ferrari");

console.log(newCarBrand) // returns a new array and does not mutate the original data. ["Porsche", "Mercedes-Benz", "Lamborghini", "Ferrari"]
console.log(fastCars) // returns our original data. ["Porsche", "Mercedes-Benz", "Lamborghini"]

That's it, you have created a function to take an array and append an element to the end of the array. Calling this function with the same arguments will return the same result, every time you call it and the original array will not be modified.

This is a pure function, which means that given the same input, will always return the same output and it produces no side effects.

Happy coding! :-)

Please feel free to comment and share my post