41

In Javascript, why is

var myArray = new Array(3);

different from:

var otherArray = [null, null, null];

?

Obs: (myArray == otherArray) returns false.

And also, how can I get a variable like otherArray, which is an array full of 'nulls`, but with whatever size i'd like?

Obs

[undefined, undefined, undefined] 

is also not equal to myArray.

Mauricio Moraes
  • 7,255
  • 5
  • 39
  • 59

6 Answers6

169

With EcmaScript 6 (ES2105), creating an array containing five nulls is as easy as this:

const arr = new Array(5).fill(null);

MDN Reference

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
lardois
  • 1,746
  • 1
  • 10
  • 7
5

This var myArray = new Array(3); will create an empty array. Hence, for this reason, myArray and otherArray are different arrays. Furthermore, even if they had the same values, three undefined values, the arrays wouldn't be the same. An array is an object and the variable myArray holds a reference to that object. Two objects with the same values aren't the same.

For instance,

var a = new Object();
var b = new Object();
console.log(a===b); // outputs false.

In addition to this:

var customerA = { name: "firstName" };
var customerB = { name: "firstName" };
console.log(customerA===customerB); // outputs false.

Update

Furthermore, in the case of var myArray = new Array(3) even the indices aren't initialized, as correctly Paul pointed out in his comment.

If you try this:

var array = [1,2,3];
console.log(Object.keys(array));

you will get as an output:

["1","2","3"];

While if you try this:

var array = new Array(3);
console.log(Object.keys(array));

you will get as output:

[]
Ahmad Habib
  • 2,053
  • 1
  • 13
  • 28
Christos
  • 53,228
  • 8
  • 76
  • 108
  • A link to a resource about sparse arrays would make it a complete answer I guess :) (about Array iteration methods) – axelduch Jan 08 '15 at 13:36
  • 2
    It's more than the items are just _undefined_, the indices aren't initialised either; – Paul S. Jan 08 '15 at 13:38
  • 1
    *"new Array(3); will create an array with three elements that are undefined"* not quite true. It creates empty array, without any values at all, even undefined (so called "holes"). it's just reading missing indexes returns `undefined`. – dfsq Jan 08 '15 at 13:42
  • @Christos `var myArray = new Array(3); will create an empty array` not quite true, should be array of length three having all empty values.. – Naeem Shaikh Jan 08 '15 at 13:45
  • @dfsq `var array = new Array(3); console.log(array.length);` This outputs 3. So how the `array` is empty? – Christos Jan 08 '15 at 13:47
  • Christos.. read my comment.. array of length three but all empty values.. i.e no value in it. Not an empty array – Naeem Shaikh Jan 08 '15 at 13:49
  • 1
    @Christos It doesn't have nor indexes nor values, only holes. It's like allocated space. In general `new Array(number)` has little useful application. – dfsq Jan 08 '15 at 13:49
  • @Christos I always find this easiest to understand as `0 in new Array(1); // false` – Paul S. Jan 08 '15 at 13:51
  • Or `Object.keys(new Array(1))` => `[]`, but `Object.keys(new Array(1,2))` => `["0", "1"]`. – dfsq Jan 08 '15 at 13:53
  • @dfsq Nice approach. I didn't think it. I will include also to my post. – Christos Jan 08 '15 at 13:55
4

The first point to note is that if you want to compare two Arrays or any other Object, you either have to loop over them or serialize them as comparing references will always give false


How can I get a variable like otherArray, which is an array full of 'nulls', but with whatever size I'd like?

Here is an alternative method for creating Arrays with a default value for its items and all indices initialised:

function createArray(len, itm) {
    var arr1 = [itm],
        arr2 = [];
    while (len > 0) {
        if (len & 1) arr2 = arr2.concat(arr1);
        arr1 = arr1.concat(arr1);
        len >>>= 1;
    }
    return arr2;
}

Now,

createArray(9, null);
// [null, null, null, null, null, null, null, null, null]
Ahmad Habib
  • 2,053
  • 1
  • 13
  • 28
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 4
    I do not understand why you wrote such a complicated function. I tested this one `function createArray2(len, itm) { var arr = []; while (len > 0) { arr.push(itm); len--;} return arr;}` I ran tests using console.time in Chrome and the results of `createArray(10000, null)` and `createArray(1000000, null)` in a 1000 forloop are: 143.964ms/98.495ms and 20114.130ms/16686.080ms the faster always being my function... Did I miss something ? – M0rkHaV Oct 31 '16 at 14:11
3

I've did some research and it turned out that the Array(length).fill(null) it not the best solution in terms of performance.

The best performance showed:

const nullArr = Array(length)
for (let i = 0; i < length; i++) {
  nullArr[i] = null
}

Just look at this:

const Benchmark = require('benchmark')
const suite = new Benchmark.Suite

const length = 10000

suite
  .add('Array#fill', function () {
    Array(length).fill(null)
  })
  .add('Array#for', function () {
    const nullArr = Array(length)
    for (let i = 0; i < length; i++) {
      nullArr[i] = null
    }
  })

  .on('cycle', function (event) {
    console.log(String(event.target))
  })
  .on('complete', function () {
    console.log('Fastest is ' + this.filter('fastest').map('name'))
  })

  .run({ async: true })

It shows the following results:

Array#fill x 44,545 ops/sec ±0.43% (91 runs sampled)
Array#for x 78,789 ops/sec ±0.35% (94 runs sampled)
Fastest is Array#for
Max Baev
  • 49
  • 1
  • 7
3

You can also try [...new Array(76)] to generate 76 undefineds.

console.log(
  [...new Array(76)]
)  

Or to fill with null.

console.log(
  [...new Array(76).fill(null)]
)  
NVRM
  • 11,480
  • 1
  • 88
  • 87
francis
  • 3,852
  • 1
  • 28
  • 30
0

this worked for me

const bucket = [Array(9).fill(null)] 
Jonathan
  • 685
  • 1
  • 10
  • 30
  • 2
    Answer needs supporting information Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – moken Jul 24 '23 at 08:31