In ES5 Javascript, how can I add an element to an array and return the new array immediately without using concat?

advertisements

I often find myself in the situation where I want to, in a single (atomic) operation, add an item to an array and return that new array.

['a', 'b'].push('c');

won't work as it returns the new length.

I know the following code works

['a', 'b'].concat(['c']);

But I find it ugly code (combining two arrays just to add a single item to the end of the first array).

I can't use Array.splice() as it modifies the original array (and returns the removed items). Array.slice() does return a shallow copy but you can't add new items.

ES6

I'm aware that in es6 you can use

[...['a', 'b'], 'c']

But I'm looking for an es5 solution

Lodash

I'm okay in using lodash

Just to be clear

I'm aware that this can be achieved in several different ways (like the Array.concat() method above), but I'm looking for an intuitive simple piece of code, which doesn't "misuses" other operators


I know the following code works ['a', 'b'].concat(['c']); But I find it ugly code (combining two arrays just to add a single item to the end of the first array).

The concat() method can be given a single (or multiple) values without the need of encapsulating the value(s) in an array first, for example:

['a', 'b'].concat('c');   // instead of .concat(['c']);

From MDN (my emphasis):

Arrays and/or values to concatenate into a new array.

Besides from that there are limited options without using extension and existing methods.

Example on how to extend the Array (this will return current array though):

Array.prototype.append = function(item) {
  this.push(item);
  return this
};

var a = [1, 2, 3];
console.log(a.append(4))

Optionally create a simple function as @torazaburo suggests, which can take array and item as argument:

function append(arr, item) {
  arr.push(item);
  return arr;
}

or using concat():

function append(arr, item) {
  return arr.concat(item)
}