0

This is a simple code that I want to add the passed parameters to the array, and then return all the array elements.

function addToArray(param) {
    const array = [];
    
    array.push(param);
    
    return array; 
}

console.log(addToArray('abc'))
console.log(addToArray(2))
console.log(addToArray('text'))

For each log it returns

[ 'abc' ]

[ 2 ]

[ 'text' ]

But I want it to return

[ 'abc' ]

[ 'abc', 2 ]

[ 'abc', 2, 'text' ]

I know I can do it if the array was outside of the function, but can I do that locally inside the function without making the variable global?

  • 1
    Not if you initialize your array inside the function; it would get created anew each time the function fires. Could you pass the array to the function? – mykaf Aug 14 '23 at 15:50

1 Answers1

3

You can do this by declaring the array outside the function. To avoid making it a global variable you can use an IIFE.

const addToArray = (function() {
  const array = [];
  return function(param) {
    array.push(param);
    return array;
  }
})();

console.log(addToArray('abc'));
console.log(addToArray(2));
console.log(addToArray('text'));
Barmar
  • 741,623
  • 53
  • 500
  • 612