skip to Main Content

I am wondering and this may be a stupid question why splice is giving me different results for apparently same situation.

one is using [] and the other one is using Array constructor

I’ve checked a bit on internet and apparently it may be about sparse values but maybe not. One thing though on one of my project I’ve used the second case and after inspecting the array, it looks like the index doesn’t start from 0 but where the array was spliced any ideas?

const arr = new Array(3)

arr.push( 1 );
arr.push( 2 );
arr.push( 3 );

arr.splice( 0, 2 );

console.log( arr[ 0 ] );
const arr = [ 1, 2, 3 ];

arr.splice( 0, 2 );

console.log( arr[ 0 ] );

2

Answers


  1. When creating array with new Array(3) constructor, your array already have three empty slots and every time you push something, you push it not to index 0, but to index 3. In the end you have

    Array(6) [ <3 empty slots>, 1, 2, 3 ]
    

    So arr[0] is actually empty slot.
    You need to set your values instead of pushing

    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    
    Login or Signup to reply.
  2. Case 1:

    When you create an array using const arr = new Array(3);, you’re creating an array object with a length of 3, where each value is undefined. Adding three values with arr.push(1), arr.push(2), and arr.push(3) would result in an array like this: [undefined, undefined, undefined, 1, 2, 3]

    Case 2:

    You start with an array containing [1, 2, 3]. Using arr.splice(0, 2) removes the first two elements [1, 2], leaving only [3]. When you log arr[0], it shows 3, as it is now the first and only element in the array.

    Ref: Array#splice

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search