With EcmaScript 6 (ES2105), creating an array containing five nulls is as easy as this:
const arr = new Array(5).fill(null);
MDN Reference
Answer from lardois on Stack OverflowWith 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:
[]
Videos
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');
}
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.
It is difficult to say why your code creates the null values without have a look to it.
But I can say you that it is not the expected behaviour.
You can see this example to get some inspiration:
var data = [
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
];
var newObjectToBeAdded = { name: "daily", amount:"100" }
function showObjects()
{
document.body.innerHTML += data + '<hr>';
}
function deleteObjectByName( objectName )
{
for( var i = 0; i < data.length; i++ )
{
if( data[ i ].name == objectName )
{
data.splice(i, 1);
}
}
}
function addObjectToData( newObject )
{
data.push( newObject );
}
showObjects();
deleteObjectByName( "quarterly" );
showObjects();
addObjectToData( newObjectToBeAdded );
showObjects();
Just to throw a guess out, maybe you are accidentally duplicating the array. Maybe in some point of your code you are doing something like this:
var new_array = original_array.splice( index );
Or creating the new array in the loop you use to find the target object, or using some kind of intermediate array, etc.
Hope it helps!
var arrayWithoutNulls = myArray.filter(function(val) {
if (val) {
return val;
}
});
Please consider the following:
var myFruits = ['Banana', 'Apple', 'Strawberry'];// SOME CODING// SOME CODINGmyFruits = undefined; // Is this better?myFruits = null; // or is this better?
Further question, what is the distinction between the two? Is there any cases where only null is used or undefined is used? Thanks.
It could happen when someone calls it without a context, e.g. Array.prototype.every(...) instead of someArray.every(...). Or a more likely case: Passing someArray.every as a callback to some other function which will then invoke it without the proper context.
Since the function is running in Strict Mode this === undefined when no context is provided. And undefined == null.
It's useful for cases like:
Array.prototype.every.call(null, ...);
You are not likely to meet that version of code, but in place of null can be a variable, that is not yet initialized, for example. In that case TypeError is only logical.