So in another answer (How can I create a two dimensional array in JavaScript?) I saw the following
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = createArray.apply(this, args);
}
return arr;
}
createArray(); // [] or new Array()
createArray(2); // new Array(2)
createArray(3, 2); // [new Array(2),
// new Array(2),
// new Array(2)]
What does this mean:
var arr = new Array(length || 0),
i = length;
The two parts I am confused about are length || 0
and the usage of the comma followed by i = length
.
For length || 0
I did some experiments and I am very confused.
Here's a JSFiddle where I try something using the variable length
and then the exact same thing with the variable blah
and only get an error on the second one: https://jsfiddle.net/vrp0uhtL/4/ you will need to go into the debugger. I've only tested this on chrome.
For ,i = length
is this just shorthand for declaring i
also as a var on the same line?
Thanks
EDIT: Because I'm finding some strange things happening and to differentiate this question similar other ones: Why is it that:
var arr = new Array(length || 0)
console.log(arr)
var arr2 = new Array(blah || 0)
console.log(arr2)
Will produce an error only on the second one, when neither length or blah have been defined elsewhere; More specifically, why does length always have a value of 0 even when I haven't defined it (see JSFiddle above)