C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript program that uses array literal
// Initialize array with 3 elements.
var values = [10, 20, 30];
console.log("ARRAY: " + values);
Output
ARRAY: 10,20,30
Warning: With one argument, we do not get a one-element Array. This specifies a capacity or initial length.
Performance: In a performance test, I found that an initial size can reduce array resizes and lead to better program performance.
JavaScript program that uses constructor, 1 argument
// Create array with 3 empty elements.
// ... Then assign them with indexes.
var values = new Array(3);
values[0] = 10;
values[1] = 20;
values[2] = 30;
console.log("EXAMPLE: " + values);
Output
EXAMPLE: 10,20,30
JavaScript program that uses constructor, 3 arguments
// Use array constructor with 2 or more arguments to create an array.
var values = new Array(10, 20, 30);
console.log("VALUES: " + values);
Output
VALUES: 10,20,30
JavaScript program that uses Array constructor, no new
// The new keyword is not required.
// ... It is removed by Closure Compiler.
var result = Array(3);
console.log("RESULT: " + result);
Output
RESULT: ,,
Sometimes: We do not know all the elements immediately. This approach allows us to add elements as soon as we know what they are.
JavaScript program that uses empty array, push
// Create an empty array and push elements to it.
var values = [];
values.push(10);
values.push(20);
values.push(30);
console.log("ELEMENTS: " + values);
Output
ELEMENTS: 10,20,30
JavaScript program that uses empty array, unshift
// Use unshift to initialize an array in reverse order.
var values = [];
values.unshift(30);
values.unshift(20);
values.unshift(10);
console.log("RESULT: " + values);
Output
RESULT: 10,20,30