Taking profit of reducethe reduce method as followingfollows:
function insert(arr, val, index) {
return index >= arr.length
? arr.concat(val)
: arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}
So atin this way we can return a new array (will be a cool functional way - more much better than use pushusing push or splicesplice) with the element inserted at index, and if the index is greater than the length of the array it will be inserted at the end.