C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part 1: Here we print the array elements by passing the string representation of the array to console.log.
Part 2: Each array has a length, and this is precomputed for the array, so no looping or counting must occur.
JavaScript program that uses array
var numbers = [10, 20, 30];
// Part 1: print the array elements.
console.log("ARRAY: " + numbers);
// Part 2: get length of array.
var length = numbers.length;
console.log("LENGTH: " + length);
Output
ARRAY: 10,20,30
LENGTH: 3
JavaScript program that uses push
// Create an empty array.
var numbers = [];
// Add two elements to the array with push calls.
numbers.push(0);
numbers.push(10);
console.log("PUSH RESULT: " + numbers);
Output
PUSH RESULT: 0,10
Tip: This is like an array capacity, but all the initial elements exist and are undefined.
JavaScript program that uses initial array size
// Use new Array with one integer to have undefined elements.
var result = new Array(5);
console.log("ARRAY: " + result);
Output
ARRAY: ,,,,
Tip: Pop() removes the last element, so it leaves no gap in the array. No elements need to be shifted forward after a pop.
JavaScript program that uses pop
var colors = ["red", "blue", "green"];
// Remove last element from the array.
var removed = colors.pop();
console.log("COLORS: " + colors);
console.log("REMOVED: " + removed);
Output
COLORS: red,blue
REMOVED: green
JavaScript program that uses indexOf
var codes = [100, 200, 300, 999];
// This is located at index 1.
var result200 = codes.indexOf(200);
console.log("RESULT FOR 200: " + result200);
// Not in the array so -1 is returned.
var result7 = codes.indexOf(7);
console.log("RESULT FOR 7: " + result7);
Output
RESULT FOR 200: 1
RESULT FOR 7: -1
Here: We have 3 "blue" strings in an array. We find the last one with lastIndexOf—its index is 2, meaning the third element.
JavaScript program that uses lastIndexOf
var colors = ["blue", "blue", "blue"];
// Find last occurring "blue" color.
var lastBlue = colors.lastIndexOf("blue");
// Print the index we found.
console.log("LAST BLUE: " + lastBlue);
Output
LAST BLUE: 2
JavaScript program that uses for-loop on array
var letters = ["x", "y", "z"];
// Loop over indexes with for-loop.
for (var i = 0; i < letters.length; i++) {
console.log("FOR: " + letters[i]);
}
Output
FOR: x
FOR: y
FOR: z
Tip: With the for-in loop on an array, we must still access the element with an index. The iteration variable is an index.
Note: The array indexes can be returned in any order by the for-in loop. So this loop is probably not the best one for arrays.
JavaScript program that uses for-in loop on array
var letters = ["g", "h", "i"];
// Loop over indexes with for-in loop.
for (var i in letters) {
console.log("FOR IN: " + letters[i]);
}
Output
FOR IN: g
FOR IN: h
FOR IN: i
JavaScript program that uses for-of loop on array
var sides = ["left", "center", "right"];
// Loop over elements with for-of.
for (var side of sides) {
console.log("FOR OF: " + side);
}
Output
FOR OF: left
FOR OF: center
FOR OF: right
JavaScript program that uses slice
var codes = [10, 20, 30, 0, -1];
// Slice receives a first index, and a last index.
// ... It returns the elements in that range.
var slice1 = codes.slice(1, 2);
var slice2 = codes.slice(1, 3);
console.log("SLICE 1: " + slice1);
console.log("SLICE 2: " + slice2);
Output
SLICE 1: 20
SLICE 2: 20,30
Argument 1: The index we want to start removing from. So to remove the second element onwards, we pass 1.
Argument 2: The count of elements we want to remove. To remove 2 elements we pass the value 2.
Finally: We pass any number of arguments to be inserted in the region specified. The array grows to accommodate these elements.
JavaScript program that uses splice
var codes = [10, 20, 30, 40];
// First argument is the index we start at.
// ... Second argument is the number of elements we remove.
// ... Then we add the following arguments.
codes.splice(1, 2, 900, 1000, 1100);
console.log("SPLICE: " + codes);
Output
SPLICE: 10,900,1000,1100,40
Note: Arrays are mutable in JavaScript. Unlike strings, we can modify them in-place with no copies.
JavaScript program that uses reverse
var colors = ["blue", "red"]
// Reverse the ordering of the array.
// ... The original is modified.
var reversed = colors.reverse();
console.log("REVERSED: " + colors);
Output
REVERSED: red,blue
JavaScript program that accesses adjacent elements
var codes = [10, 20, 25, 35];
// Loop over adjacent elements (pairs) in the array.
for (var i = 1; i < codes.length; i += 2) {
// Write left and right elements.
var left = codes[i - 1];
var right = codes[i];
console.log("LEFT: " + left);
console.log(" RIGHT: " + right);
}
Output
LEFT: 10
RIGHT: 20
LEFT: 25
RIGHT: 35
And: This saves memory. Engines like V8 decide when to use sparse arrays with logical rules (heuristics).
JavaScript program that uses sparse array
// Create an array.
var results = [];
// Only two elements are assigned in this sparse array.
results[99999] = 5;
results[1] = 0;
console.log("SPARSE LENGTH: " + results.length);
console.log("SPARSE LAST: " + results[99999]);
Output
SPARSE LENGTH: 100000
SPARSE LAST: 5
Note: It is possible to modify arrays. But often for best performance, leaving arrays alone and using indexes to access them is best.
JavaScript program that uses shift
var gems = ["ruby", "sapphire", "crystal"];
console.log("BEFORE: " + gems);
// Shift returns the first element in the array.
// ... It also removes that element from the array.
var shifted = gems.shift();
console.log("SHIFTED: " + shifted);
Output
BEFORE: ruby,sapphire,crystal
SHIFTED: ruby
Note: No quotes are in the output string. So if a string contains a comma, it may be impossible to convert this string back into an array.
JSON: For a way to convert an array into a string format that can be reused with no data loss, consider JSON.stringify.
JSONJavaScript program that uses toString
var words = ["note", "tip", "information"];
// Convert array to string.
var result = words.toString();
// Write result and length.
console.log("STRING: " + result);
console.log("LENGTH: " + result.length);
Output
STRING: note,tip,information
LENGTH: 20
Tip: Join is the opposite of split. If the delimiter is not found in any of the strings, we can use split() to reverse a join.
JavaScript program that uses join
var vehicles = ["car", "train", "plane", "boat"];
// Join with a delimiter character.
var result = vehicles.join("/");
console.log("JOINED: " + result);
Output
JOINED: car/train/plane/boat
Here: We call forEach on an array, and call the handleElement function on each individual element.
Tip: Using forEach instead of a for-loop can reduce errors and lead to more elegant code.
JavaScript program that uses forEach function on array
function handleElement(x) {
"use strict";
// This is called on each element in the array.
console.log("FOREACH: " + x)
console.log("FOREACH TIMES 2: " + (x * 2));
}
var numbers = [15, 1, -15];
// Use forEach function to iterate an array.
// ... Pass name of function to forEach.
numbers.forEach(handleElement);
Output
FOREACH: 15
FOREACH TIMES 2: 30
FOREACH: 1
FOREACH TIMES 2: 2
FOREACH: -15
FOREACH TIMES 2: -30
Version 1: This version of the code uses the push method to add elements onto the end of an array.
Version 2: This version uses unshift to place elements onto the start of the array. The total time required is recorded.
Result: When adding elements to an array, push() is a faster option than unshift. Push is optimized better in browsers.
JavaScript program that benchmarks array push
var x1 = performance.now();
// Version 1: create an array and push 1000 numbers to it.
for (var i = 0; i < 100000; i++) {
var numbers = [];
for (var x = 0; x < 1000; x++) {
numbers.push(x);
}
}
var x2 = performance.now();
// Version 2: insert elements at start of array with unshift.
for (var i = 0; i < 100000; i++) {
var numbers = [];
for (var x = 0; x < 1000; x++) {
numbers.unshift(x);
}
}
var x3 = performance.now();
// Results.
console.log("TIME 1: " + (x2 - x1));
console.log("TIME 2: " + (x3 - x2));
Output
TIME 1 (2019): 407.565
TIME 2: 8707.960
Version 1: This version of the code create a 1-element array with an inline literal expression.
Version 2: This version creates an empty array, and then calls push() to add 1 element to the array.
Result: Using a single expression with literal syntax is faster in Chromium. Reducing method calls (like push) tends to help performance.
JavaScript program that times literal with 1 element
var x1 = performance.now();
// Version 1: create 1-element array with literal syntax.
for (var i = 0; i < 10000000; i++) {
var test = [1];
}
var x2 = performance.now();
// Version 2: create 1-element array with empty literal and push.
for (var i = 0; i < 10000000; i++) {
var test = [];
test.push(1);
}
var x3 = performance.now();
// Results.
console.log("TIME 1: " + (x2 - x1));
console.log("TIME 2: " + (x3 - x2));
Output
TIME 1 (2019): 88.255
TIME 2: 240.394
Version 1: This version of the code calls push() to add elements to an empty array. The array may resize if needed.
Version 2: Here we just assign to indexes past the end of the array to create new elements, forcing the array to resize.
Result: In Chromium, assignment performs lightly better. But even in a long-running simulation this difference is small.
JavaScript program that benchmarks push
var x1 = performance.now();
// Version 1: append to an array with push.
for (var i = 0; i < 1000000; i++) {
var test = [];
for (var x = 0; x < 10; x++) {
test.push(5000);
}
}
var x2 = performance.now();
// Version 2: append to an array with assignment.
for (var i = 0; i < 1000000; i++) {
var test = [];
for (var x = 0; x < 10; x++) {
test[x] = 5000;
}
}
var x3 = performance.now();
// Results.
console.log("TIME 1: " + (x2 - x1));
console.log("TIME 2: " + (x3 - x2));
Output
TIME 1 (2019): 47.484
TIME 2: 44.895
Version 1: This version of the code uses an empty array literal and appends 200 elements with the push method.
Version 2: This code uses "new Array(200)" and assigns the 200 undefined elements. The array should never resize.
Result: Version 2 is faster as the array is never resized—it has all 200 elements at creation time and never resizes, unlike program 1.
JavaScript program that benchmarks empty array
var x1 = performance.now();
// Version 1: add 200 elements to an empty array.
for (var i = 0; i < 1000000; i++) {
var result = [];
for (var x = 0; x < 200; x++) {
result.push(x);
}
}
var x2 = performance.now();
// Version 2: create 200 undefined elements and assign them.
for (var i = 0; i < 1000000; i++) {
var result = new Array(200);
for (var x = 0; x < 200; x++) {
result[x] = x;
}
}
var x3 = performance.now();
// Results.
console.log("TIME 1: " + (x2 - x1));
console.log("TIME 2: " + (x3 - x2));
Output
TIME 1 (2019): 729.010
TIME 2: 536.070