JavaScript – why Array.prototype.fill actually fills a “pointer” of object when filling anything like ‘new Object()’

I was trying to used Array.prototype.fill method to create a n x n 2D array but the code was buggy and I eventually found out all arrays inside are actually “pointers” to the same array.

Sample:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var matrix = new Array(10).fill(new Array(10), 0);
</code>
<code>var matrix = new Array(10).fill(new Array(10), 0); </code>
var matrix = new Array(10).fill(new Array(10), 0);

I thought conceptually this could create a 10 x 10 2D array. However if I assign value to matrix[0][0]:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>matrix[0][0] = 1;
</code>
<code>matrix[0][0] = 1; </code>
matrix[0][0] = 1;

The result will actually be:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>matrix[0][0] === 1;
matrix[1][0] === 1;
matrix[2][0] === 1;
matrix[3][0] === 1;
matrix[4][0] === 1;
matrix[5][0] === 1;
matrix[6][0] === 1;
matrix[7][0] === 1;
matrix[8][0] === 1;
matrix[9][0] === 1;
</code>
<code>matrix[0][0] === 1; matrix[1][0] === 1; matrix[2][0] === 1; matrix[3][0] === 1; matrix[4][0] === 1; matrix[5][0] === 1; matrix[6][0] === 1; matrix[7][0] === 1; matrix[8][0] === 1; matrix[9][0] === 1; </code>
matrix[0][0] === 1;
matrix[1][0] === 1;
matrix[2][0] === 1;
matrix[3][0] === 1;
matrix[4][0] === 1;
matrix[5][0] === 1;
matrix[6][0] === 1;
matrix[7][0] === 1;
matrix[8][0] === 1;
matrix[9][0] === 1;

and every time if I tried to assign value to any of the position in the matrix, all corresponding positions in other sub-arrays will change as well.

I am wondering why it’s happening?

Can anyone please answer this head-scratching question?

1

I am wondering why it’s happening?

Array#fill takes the value you give it as the first argument, and fills the array with copies of that value.

The value you’re giving it is a reference to an array, so naturally what it gives you back is an array filled with copies of that reference. Not copies of the array, copies of the reference.

E.g., it behaves this way for exactly the same reason this code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var a = new Array(10);
var b = a;
</code>
<code>var a = new Array(10); var b = a; </code>
var a = new Array(10);
var b = a;

…leaves us with a and b both referring to the same array (both containing the same value; a reference to the single array we’ve created).

Let’s throw some Unicode-art at it:

After this code runs:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var a = new Array(10);
var b = a;
</code>
<code>var a = new Array(10); var b = a; </code>
var a = new Array(10);
var b = a;

we have this in memory (minus a few irrelevant details):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
a:Ref89895−−−+
|
| +−−−−−−−−−−−−−−−+
+−−−−−>| array |
| +−−−−−−−−−−−−−−−+
| | length: 10 |
b:Ref89895−−−+ +−−−−−−−−−−−−−−−+
a:Ref89895−−−+ | | +−−−−−−−−−−−−−−−+ +−−−−−>| array | | +−−−−−−−−−−−−−−−+ | | length: 10 | b:Ref89895−−−+ +−−−−−−−−−−−−−−−+
a:Ref89895−−−+
             |
             |      +−−−−−−−−−−−−−−−+
             +−−−−−>|     array     |
             |      +−−−−−−−−−−−−−−−+
             |      | length: 10    |
b:Ref89895−−−+      +−−−−−−−−−−−−−−−+

a and b contain a reference, which I’ve shown here as Ref89895 although we never see the actual value. That’s what’s copied by b = a, not the array itself.

Similarly, when you do:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var matrix = new Array(10).fill(new Array(10), 0);
</code>
<code>var matrix = new Array(10).fill(new Array(10), 0); </code>
var matrix = new Array(10).fill(new Array(10), 0);

you end up with

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
+−−−−−−−−−−−−−−−+
matrix:Ref89895−−−>| array |
+−−−−−−−−−−−−−−−+
| length: 10 |
| 0: Ref55462 |--
| 1: Ref55462 |--\
| 2: Ref55462 |--\
| 3: Ref55462 |--\\ +−−−−−−−−−−−−−−−+
| 4: Ref55462 |---+++++->| array |
| 5: Ref55462 |--///// +−−−−−−−−−−−−−−−+
| 6: Ref55462 |--//// | length: 10 |
| 7: Ref55462 |--/// +−−−−−−−−−−−−−−−+
| 8: Ref55462 |--//
| 9: Ref55462 |--/
+−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−+ matrix:Ref89895−−−>| array | +−−−−−−−−−−−−−−−+ | length: 10 | | 0: Ref55462 |-- | 1: Ref55462 |--\ | 2: Ref55462 |--\ | 3: Ref55462 |--\\ +−−−−−−−−−−−−−−−+ | 4: Ref55462 |---+++++->| array | | 5: Ref55462 |--///// +−−−−−−−−−−−−−−−+ | 6: Ref55462 |--//// | length: 10 | | 7: Ref55462 |--/// +−−−−−−−−−−−−−−−+ | 8: Ref55462 |--// | 9: Ref55462 |--/ +−−−−−−−−−−−−−−−+
                   +−−−−−−−−−−−−−−−+
matrix:Ref89895−−−>|     array     |
                   +−−−−−−−−−−−−−−−+
                   | length: 10    |
                   | 0: Ref55462   |--
                   | 1: Ref55462   |--\
                   | 2: Ref55462   |--\
                   | 3: Ref55462   |--\\    +−−−−−−−−−−−−−−−+
                   | 4: Ref55462   |---+++++->|     array     |
                   | 5: Ref55462   |--/////   +−−−−−−−−−−−−−−−+
                   | 6: Ref55462   |--////    | length: 10    |
                   | 7: Ref55462   |--///     +−−−−−−−−−−−−−−−+
                   | 8: Ref55462   |--//
                   | 9: Ref55462   |--/
                   +−−−−−−−−−−−−−−−+

To create a 10-place array where each of the 10 places is itself a 10-place array of 0, I’d probably use either Array.from or fill with map:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// Array.from
var matrix = Array.from({length: 10}, function() {
return new Array(10).fill(0);
});
// fill and map
var matrix = new Array(10).fill().map(function() {
return new Array(10).fill(0);
});
</code>
<code>// Array.from var matrix = Array.from({length: 10}, function() { return new Array(10).fill(0); }); // fill and map var matrix = new Array(10).fill().map(function() { return new Array(10).fill(0); }); </code>
// Array.from
var matrix = Array.from({length: 10}, function() {
    return new Array(10).fill(0);
});

// fill and map
var matrix = new Array(10).fill().map(function() {
    return new Array(10).fill(0);
});

or in ES2015:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// Array.from
let matrix = Array.from({length: 10}, () => new Array(10).fill(0));
// fill and map
let matrix = new Array(10).fill().map(() => new Array(10).fill(0));
</code>
<code>// Array.from let matrix = Array.from({length: 10}, () => new Array(10).fill(0)); // fill and map let matrix = new Array(10).fill().map(() => new Array(10).fill(0)); </code>
// Array.from
let matrix = Array.from({length: 10}, () => new Array(10).fill(0));

// fill and map
let matrix = new Array(10).fill().map(() => new Array(10).fill(0));

3

This is because when you’re calling array.fill() you’re only passing it a single new Array() value. That’s the point, to fill an array with a single value.

If you want to take an existing array and assign a new instance to each index you could use .map().

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var matrix = new Array(10).fill().map(function(item, index, arr) {
return new Array(10);
});
</code>
<code>var matrix = new Array(10).fill().map(function(item, index, arr) { return new Array(10); }); </code>
var matrix = new Array(10).fill().map(function(item, index, arr) {
    return new Array(10);
});

To do this in the nested fashion you seem to want you can map twice.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// the callback function's item, index and array properties are optional
var matrix = new Array(10).fill().map(function(item, index, arr) {
return new Array(10).fill(0);
});
</code>
<code>// the callback function's item, index and array properties are optional var matrix = new Array(10).fill().map(function(item, index, arr) { return new Array(10).fill(0); }); </code>
// the callback function's item, index and array properties are optional
var matrix = new Array(10).fill().map(function(item, index, arr) {
    return new Array(10).fill(0);
});

If you’re using ES6, this can be further simplified to a one-liner.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var matrix = new Array(10).fill().map(() => new Array(10).fill(0));
</code>
<code>var matrix = new Array(10).fill().map(() => new Array(10).fill(0)); </code>
var matrix = new Array(10).fill().map(() => new Array(10).fill(0));

The reason .map() works is because it calls the supplied callback function for each item in the array.

The reason for the blank .fill() before the .map() is to populate the array with values. By default a new array that’s been given a size has undefined for every item. .fill() will temporarily populate the array so it can be mapped.

0

In your particular case, since Array.prototype.fill() fills with a single value and in JS objects (such as arrays) are reference types you have all indices carry a reference to the first one. In JS creating an ND array may not be as simple as it seems since arrays will be copied by reference. For a general purpose arrayND function you need an array cloning utility function. Let’s see;

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Array.prototype.clone = function(){
return this.map(e => Array.isArray(e) ? e.clone() : e);
};
function arrayND(...n){
return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
}
var array3D = arrayND(5,5,5,"five");
array3D[0][1][2] = 5;
console.log(array3D);</code>
<code>Array.prototype.clone = function(){ return this.map(e => Array.isArray(e) ? e.clone() : e); }; function arrayND(...n){ return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p )); } var array3D = arrayND(5,5,5,"five"); array3D[0][1][2] = 5; console.log(array3D);</code>
Array.prototype.clone = function(){
  return this.map(e => Array.isArray(e) ? e.clone() : e);
};
function arrayND(...n){
  return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
}
var array3D = arrayND(5,5,5,"five");
array3D[0][1][2] = 5;
console.log(array3D);

arrayND function takes indefinite number of arguments. The last one designates the default value to fill our ND array and the preceding arguments are the sizes of each dimension they represent. (first argument is dimension 1, second argument is dimension 2 etc…)

1

With recursion you can make even more dimensions 😉

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const range = r => Array(r).fill().map((v, i) => i);
const range2d = (x, y) => range(x).map(i => range(y));
const rangeMatrix = (...ranges) => (function ranger(ranged) {
return ranges.length ? ranger(range(ranges.pop()).map(i => ranged)) : ranged
})(range(ranges.pop()));
let arr10x10 = range2d(10, 10);
let arr3x5 = range2d(3, 2);
let arr4x3 = rangeMatrix(4, 3);
let arr4x3x2 = rangeMatrix(4, 3, 2);
let arr4x3x2x5 = rangeMatrix(4, 3, 2, 5);
console.log(arr10x10);
console.log(arr3x5);
console.log(arr4x3);
console.log(arr4x3x2);
console.log(arr4x3x2x5);</code>
<code>const range = r => Array(r).fill().map((v, i) => i); const range2d = (x, y) => range(x).map(i => range(y)); const rangeMatrix = (...ranges) => (function ranger(ranged) { return ranges.length ? ranger(range(ranges.pop()).map(i => ranged)) : ranged })(range(ranges.pop())); let arr10x10 = range2d(10, 10); let arr3x5 = range2d(3, 2); let arr4x3 = rangeMatrix(4, 3); let arr4x3x2 = rangeMatrix(4, 3, 2); let arr4x3x2x5 = rangeMatrix(4, 3, 2, 5); console.log(arr10x10); console.log(arr3x5); console.log(arr4x3); console.log(arr4x3x2); console.log(arr4x3x2x5);</code>
const range = r => Array(r).fill().map((v, i) => i);
const range2d = (x, y) => range(x).map(i => range(y));
const rangeMatrix = (...ranges) => (function ranger(ranged) {
  return ranges.length ? ranger(range(ranges.pop()).map(i => ranged)) : ranged
})(range(ranges.pop()));

let arr10x10 = range2d(10, 10);
let arr3x5 = range2d(3, 2);
let arr4x3 = rangeMatrix(4, 3);
let arr4x3x2 = rangeMatrix(4, 3, 2);
let arr4x3x2x5 = rangeMatrix(4, 3, 2, 5);

console.log(arr10x10);
console.log(arr3x5);
console.log(arr4x3);
console.log(arr4x3x2);
console.log(arr4x3x2x5);

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật