create 3 undefined, empty array.
var a1 = [,,,];
var a2 = new Array(3);
from JavaScript: The Definitive Guide,
0 in a1 //true
0 in a2 //false
but, in real world browser, getting different result. (IE8 and chrome 33...)
0 in a1 //false
0 in a2 //false
which is true, book or real world?
In JavaScript, the array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.
Logical AND (&&) Relational expressions always evaluate to true or false , so when used like this, the && operator itself returns true or false . Relational operators have higher precedence than && (and || ), so expressions like these can safely be written without parentheses.
JavaScript's expression is a valid set of literals, variables, operators, and expressions that evaluate to a single value that is an expression. This single value can be a number, a string, or a logical value as depending on expression. The Complete List of JavaScript Expressions are listed below: Primary Expressions.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
Looks like the book is wrong. As you can see from the specification, [,,,]
does not add any values to the array:
The production ArrayLiteral : [ Elisionopt ] is evaluated as follows:
- Let array be the result of creating a new object as if by the expression new Array() where Array is the standard built-in constructor with that name.
- Let pad be the result of evaluating Elision; if not present, use the numeric value zero.
- Call the
[[Put]]
internal method of array with arguments "length", pad, and false.- Return array.
("Elisions" are the ,
which are not preceded or followed by an expression.)
In simpler terms:
,
, which is basically just counting them, starting from 1.
So ,,,
results in 3.length
of the array to the result (e.g. 3). And that's exactly what new Array(3)
is doing as well.
There is also a less formal description of elided elements:
Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With