Chapter 5. Working with Arrays and Loops
5.0. Introduction
An array is an ordered collection of elements. In JavaScript, an array can be created using formal object notation, or it can be initialized using literal notation, as demonstrated in the following code:
var arrObject = new Array("val1", "val2"); // array as object
var arrLiteral = ["val1", "val2"]; // array literalTo the developer, there is no difference: you can invoke an Array method on both a literal and an object.
However, to the JavaScript engine, an array literal has to be
reinterpreted each time it’s accessed, especially
when used in a function call. On the positive side, though, array literals
can replace the need for temporary variables, especially when sending
values to a function.
A new Array object is created
using the new operator, as
follows:
var arrObject = new Array();
You can also create a new array that has some values:
var arrObject = new Array("val1","val2");You can create an array literal by using square brackets to hold the array values. For instance, you can define an array literal and assign it to a variable:
var arrLiteral = ["val1","val2","val3"];
You can also create, and use, a literal array in a function or method call:
someFunction("param1", ["val1","val2"]);Note, though, that when you pass a variable containing an array
literal to a function, it is passed by reference—the same as passing a
variable holding an Array object. Changes to the variable in the function are reflected outside of the function: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access