How to limit array size with JavaScript?

Sometimes, we want to limit array size with JavaScript.

In this article, we’ll look at how to limit array size with JavaScript.

How to limit array size with JavaScript?

To limit array size with JavaScript, we can use the array slice method.

For instance, we write:

const arr = [1, 2, 3]
const add = (a, x) => [x, ...a.slice(0, a.length - 1)];
console.log(add(arr, 4))

to define the add function that takes an array a and value x that we prepend to the returned array.

We keep the returned array the same size as a by calling slice with 0 and a.length - 1 to discard the last item in a.

Therefore, the console log logs [4, 1, 2].

Conclusion

To limit array size with JavaScript, we can use the array slice method.