-3

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 ] );
JSmith
  • 4,519
  • 4
  • 29
  • 45
  • 3
    Not sure I get your title: splice() is returning a value, but you're not capturing the result of splice() in a variable? Also don't use the Array() constructor. There is no such thing as a "fixed length array" in JS, only "arrays that had their length property explicit set to a lie", so you're adding elements to an array that thinks its first three elements already exist =) – Mike 'Pomax' Kamermans Apr 29 '23 at 19:45
  • 2
    `for apparently same situation.` Its not. `console.log` your arrays, they are entirely different. – tkausl Apr 29 '23 at 19:45
  • 2
    In your first example, you generate an array of `[undefined, undefined, undefined, 1, 2, 3]` – j08691 Apr 29 '23 at 19:46
  • Does this answer your question? [How to initialize an array's length in JavaScript?](https://stackoverflow.com/questions/4852017/how-to-initialize-an-arrays-length-in-javascript) – miken32 Apr 30 '23 at 01:54
  • @miken32 this was a stupid mistake from my side – JSmith Apr 30 '23 at 01:58

2 Answers2

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;
Andyally
  • 863
  • 1
  • 9
  • 22
1

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

XMehdi01
  • 5,538
  • 2
  • 10
  • 34