Given that there are only 2 potential values for each item in the 2D array, you will avoid allocating extra memory if you actually don't initialize the whole 2D array since JS arrays are essentially hashes (good explanation here: https://stackoverflow.com/a/20323491/2611078).
Initialize array:
var arr = [];
Then, when updating an item after user action:
if (!arr[i]) {
arr[i] = [];
}
arr[i][j] = true;
Then, when checking the array:
if (arr[i] && arr[i][j]) {
console.log('value');
} else {
console.log('other (default) value');
}
Answer from Julie on Stack OverflowGiven that there are only 2 potential values for each item in the 2D array, you will avoid allocating extra memory if you actually don't initialize the whole 2D array since JS arrays are essentially hashes (good explanation here: https://stackoverflow.com/a/20323491/2611078).
Initialize array:
var arr = [];
Then, when updating an item after user action:
if (!arr[i]) {
arr[i] = [];
}
arr[i][j] = true;
Then, when checking the array:
if (arr[i] && arr[i][j]) {
console.log('value');
} else {
console.log('other (default) value');
}
See How do you easily create empty matrices javascript? for a discussion of this topic.
I would say the interviewer is right: there is no need for all your nulls.
arr: [null, null, null, null, null],
For this, arr: Array(5) would be fine. Or, you could show off and do [,,,,,].
initialize: function() {
for (var i = 0 ; i < arr.length; i++) {
arr[i] = [null, null, null, null, null];
}
For this, arr[i] = Array(5) would also be fine.
You're just boxing out the dimensions of the two-dimensional array; why put in all the nulls? And definitely not empty strings--that would have gotten you booted out of the interview even more quickly.
Videos
With EcmaScript 6 (ES2105), creating an array containing five nulls is as easy as this:
const arr = new Array(5).fill(null);
MDN Reference
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:
[]