Avatar ·

How to insert an element into an array at a specified index in JavaScript?

Hello everyone! I just started learning JavaScript and ran into a problem when working with arrays. I need to insert a new element not at the end or beginning of the array, but in the middle — at a specific index. For example, I have an array of numbers `[1, 2, 4, 5]`, and I want to insert the number `3` at index 2 (so that it becomes `[1, 2, 3, 4, 5]`). \n\nI know about the `push()` method (adds to the end) and `unshift()` (adds to the beginning), but they don't work. I tried writing something like:\n```javascript\nlet arr = [1, 2, 4, 5];\narr[2] = 3;\nconsole.log(arr); // [1, 2, 3, 5] — the number 4 disappeared!\n```\nAs you can see, simple assignment by index replaces the existing element, not inserts a new one. How can I insert an element so that the rest shift to the right? \n\nPlease tell me, is there a way in JavaScript to do this correctly?