JavaScript to push value in empty index in array

To push value in an empty index in an array, we can create a custom method that finds the first empty slot and fills it, or appends to the end if no empty slots exist.

Arrays in JavaScript can have empty slots (also called sparse arrays) where certain indexes are undefined. When working with such arrays, you might need to fill these gaps before adding new elements at the end.

Understanding Empty Slots in Arrays

Empty slots occur when you skip indexes during array creation or deletion:

const arr = [1, 2, , 4, , 6];  // Empty slots at index 2 and 4
console.log(arr.length);       // 6
console.log(arr[2]);           // undefined
console.log(2 in arr);         // false - slot doesn't exist
6
undefined
false

Method 1: Using Array.prototype Extension

We can extend the Array prototype to add a pushAtEmpty() method:

Array.prototype.pushAtEmpty = function(element) {
    for (let i = 0; i 

Original array: [ 10, 20, , 40, , 60 ]
Added 99 at index: 2
Array after first push: [ 10, 20, 99, 40, , 60 ]
Added 88 at index: 4
Array after second push: [ 10, 20, 99, 40, 88, 60 ]
Added 77 at index: 6
Final array: [ 10, 20, 99, 40, 88, 60, 77 ]

Method 2: Standalone Function Approach

For better practice, avoid modifying built-in prototypes and use a standalone function:

function pushAtEmpty(arr, element) {
    for (let i = 0; i 

Original: [ 'apple', , 'banana', , 'orange' ]
After adding grape: [ 'apple', 'grape', 'banana', , 'orange' ]
After adding mango: [ 'apple', 'grape', 'banana', 'mango', 'orange' ]
After adding kiwi: [ 'apple', 'grape', 'banana', 'mango', 'orange', 'kiwi' ]

Key Points

  • Use !(i in array) to check for empty slots, not array[i] === undefined
  • Empty slots are different from undefined values
  • The function returns the index where the element was inserted
  • Prefer standalone functions over prototype modification

Conclusion

This approach efficiently fills empty array slots before appending new elements. Use the standalone function version for cleaner, more maintainable code that doesn't modify built-in prototypes.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements