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:
[]
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.
Videos
A side note: Your solution doesn't actually check for an all-null array. It just checks for an all-falsey array. [0, false, ''] would still pass the check.
You could use the Array#every method to check that every element of an array meets a certain condition:
const arr = [null, null, null];
console.log(arr.every(element => element === null));
every takes a callback in which the first argument is the current element being iterated over. The callback returns true if the element is null, and false if it is not. If, for all the elements, the callback returns true, it will evaluate to true, thus if all elements in the array are null, it's true.
You can use Array#every or lodash's _.every() with _.isNull():
var emp = [null, null, null];
var result = emp.every(_.isNull);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Use some which returns a boolean:
const arr = [null, 2, null, null];
const arr2 = [null, null, null, null];
function otherThanNull(arr) {
return arr.some(el => el !== null);
}
console.log(otherThanNull(arr));
console.log(otherThanNull(arr2));
Run code snippetEdit code snippet Hide Results Copy Expand
In recent versions of Chrome, Safari, and Firefox (and future versions of other browsers), you can use findIndex() to find the index of the first non-null element.
var arr = [null, null, "not null", null];
var first = arr.findIndex(
function(el) {
return (el !== null);
}
);
console.log(first);
Run code snippetEdit code snippet Hide Results Copy Expand
(for other browsers, there's a polyfill for findIndex())
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.
If you have a DOM node in an array in javascript and then remove it from the DOM (e.g. after your ajax call), the node will continue to exist in the array, and continue to take up space. You can then add it to the DOM again later if you wish.
If you do not add it to the DOM again, and instead set the item in the array to some other value such as null or undefined, assuming that there are no remaining references to that element, it will be garbage collected and no longer take up space.
It's worth bearing in mind that there is a difference between a javascript array and a NodeList or a HTMLCollection. You can get a node list by calling some DOM methods such as document.getElementsByTagName. NodeLists look a bit like arrays, but remain 'live', so if a node is removed from the DOM it will be removed from the NodeList too.
If a DOM element is removed from the active page, references to it are not turned to null. The elements will be stored in memory until such time as no more references to the elements exist and the garbage collector has collected the garbage.
What this means is that you'd be able to use an array of DOM nodes to restore those nodes should they be removed from their parent elements.
I would make it way more simpler without the counter. You have the total in the length of the array.
I also added a version using array.reduce().
And please, don't use numbers variable inside the function. It makes no sense here. You pass the variable to the function and inside the function you should use the received variable or it will behave incorrectly. Inside the function numbers is called "arr", so use arr all the way.
function average(arr){
if (arr.length === 0) return null;
let total = 0;
arr.forEach(function(item){
total += item;
})
return total / arr.length;
}
// using array.reduce() which makes more sense here
function average2(arr){
if (arr.length === 0) return null;
const total = arr.reduce(function(prev,next){
return prev + next;
});
return total / arr.length;
}
console.log(average([]));
console.log(average([1,2,3]));
console.log(average2([]));
console.log(average2([1,2,3]));
You don't need to test for []. If the array has a length of zero, then it's empty:
let numbers = [1, 2, 3]
function average(array) {
var total = 0;
var count = 0;
// No need to iterate over array if it's empty
if (array.length > 0) {
array.forEach(function(item) {
total += item;
count++;
})
return total / count;
} else {
// If we got here, array.length === 0
return null
}
}
console.log(average(numbers));
numbers = [];
console.log(average(numbers));