Javascript key points-Arrays
To create an array with non-zero length, but without any items, either of the following can be used:
// This...
let arr = new Array(arrayLength)
// ...results in the same array as this
let arr = Array(arrayLength)
// This has exactly the same effect
let arr = []
arr.length = arrayLength
If you wish to initialize an array with a single element, and the element happens to be a Number
, you must use the bracket syntax. When a single Number
value is passed to the Array()
constructor or function, it is interpreted as an arrayLength
, not as a single element.
let arr = [42] // Creates an array with only one element:
// the number 42.let arr = Array(42) // Creates an array with no elements
// and arr.length set to 42.
//
// This is equivalent to:
let arr = []
arr.length = 42
Calling Array(N)
results in a RangeError
, if N
is a non-whole number whose fractional portion is non-zero. The following example illustrates this behavior.
let arr = Array(9.3) // RangeError: Invalid array length
In ES2015, you can use the Array.of
static method to create arrays with single element.
let wisenArray = Array.of(9.3) // wisenArray contains only one element 9.3
Note: If you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element.
let arr = []
arr[3.4] = 'Oranges'
console.log(arr.length) // 0
console.log(arr.hasOwnProperty(3.4)) // true
Understanding length:
let cats = []
cats[30] = ['Dusty']
console.log(cats.length) // 31
You can also assign to the length
property.
Writing a value that is shorter than the number of stored items truncates the array. Writing 0
empties it entirely:
let cats = ['Dusty', 'Misty', 'Twiggy']
console.log(cats.length) // 3cats.length = 2
console.log(cats) // logs "Dusty, Misty" - Twiggy has been removedcats.length = 0
console.log(cats) // logs []; the cats array is emptycats.length = 3
console.log(cats) // logs [ <3 empty items> ]
If you know that none of the elements in your array evaluate to false
in a boolean context—if your array consists only of DOM nodes, for example—you can use a more efficient idiom:
let divs = document.getElementsByTagName('div')
for (let i = 0, div; div = divs[i]; i++) {
/* Process div in some way */
}
This avoids the overhead of checking the length of the array, and ensures that the div
variable is reassigned to the current item each time around the loop for added convenience.
For-each:
Note that the elements of an array that are omitted when the array is defined are not listed when iterating by forEach
, but are listed when undefined
has been manually assigned to the element:
let array = ['first', 'second', , 'fourth']array.forEach(function(element) {
console.log(element)
})
// first
// second
// fourthif (array[2] === undefined) {
console.log('array[2] is undefined') // true
} array = ['first', 'second', undefined, 'fourth']array.forEach(function(element) {
console.log(element)
})
// first
// second
// undefined
// fourth
Note:Since JavaScript elements are saved as standard object properties, it is not advisable to iterate through JavaScript arrays using for...in
loops, because normal elements and all enumerable properties will be listed.
Array Methods:
slice(start_index, upto_index)
extracts a section of an array and returns a new array.
let myArray = new Array('a', 'b', 'c', 'd', 'e')
myArray = myArray.slice(1, 4) // starts at index 1 and extracts all elements
// until index 3, returning [ "b", "c", "d"]
splice(index, count_to_remove, addElement1, addElement2, ...)
removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.
let myArray = new Array('1', '2', '3', '4', '5')
myArray.splice(1, 3, 'a', 'b', 'c', 'd')
// myArray is now ["1", "a", "b", "c", "d", "5"]
// This code started at index one (or where the "2" was),
// removed 3 elements there, and then inserted all consecutive
// elements in its place.
indexOf(searchElement[, fromIndex])
searches the array for searchElement
and returns the index of the first match.
let a = ['a', 'b', 'a', 'b', 'a']
console.log(a.indexOf('b')) // logs 1// Now try again, starting from after the last match
console.log(a.indexOf('b', 2)) // logs 3
console.log(a.indexOf('z')) // logs -1, because 'z' was not found
lastIndexOf(searchElement[, fromIndex])
works like indexOf
, but starts at the end and searches backwards.
let a = ['a', 'b', 'c', 'd', 'a', 'b']
console.log(a.lastIndexOf('b')) // logs 5// Now try again, starting from before the last match
console.log(a.lastIndexOf('b', 4)) // logs 1
console.log(a.lastIndexOf('z')) // logs -1
forEach(callback[, thisObject])
executes callback
on every array item and returns undefined
.
let a = ['a', 'b', 'c']
a.forEach(function(element) { console.log(element) })
// logs each item in turn
map(callback[, thisObject])
returns a new array of the return value from executing callback
on every array item.
let a1 = ['a', 'b', 'c']
let a2 = a1.map(function(item) { return item.toUpperCase() })
console.log(a2) // logs ['A', 'B', 'C']
filter(callback[, thisObject])
returns a new array containing the items for which callback
returned true
.
let a1 = ['a', 10, 'b', 20, 'c', 30]
let a2 = a1.filter(function(item) { return typeof item === 'number'; })
console.log(a2) // logs [10, 20, 30]
every(callback[, thisObject])
returns true
if callback
returns true
for every item in the array.
function isNumber(value) {
return typeof value === 'number'
}
let a1 = [1, 2, 3]
console.log(a1.every(isNumber)) // logs true
let a2 = [1, '2', 3]
console.log(a2.every(isNumber)) // logs false
some(callback[, thisObject])
returns true
if callback
returns true
for at least one item in the array.
function isNumber(value) {
return typeof value === 'number'
}
let a1 = [1, 2, 3]
console.log(a1.some(isNumber)) // logs true
let a2 = [1, '2', 3]
console.log(a2.some(isNumber)) // logs true
let a3 = ['1', '2', '3']
console.log(a3.some(isNumber)) // logs false
reduce(callback[, initialValue])
applies callback(accumulator, currentValue[, currentIndex[, array]])
for each value in the array for the purpose of reducing the list of items down to a single value. The reduce
function returns the final value returned by callback
function.
If initialValue
is specified, then callback
is called with initialValue
as the first parameter value and the value of the first item in the array as the second parameter value.
If initialValue
is not specified, then callback
's first two parameter values will be the first and second elements of the array. On every subsequent call, the first parameter's value will be whatever callback
returned on the previous call, and the second parameter's value will be the next value in the array.
If callback
needs access to the index of the item being processed, on access to the entire array, they are available as optional parameters.
let a = [10, 20, 30]
let total = a.reduce(function(accumulator, currentValue) { return accumulator + currentValue }, 0)
console.log(total) // Prints 60
reduceRight(callback[, initialValue])
works like reduce()
, but starts with the last element.
reduce
and reduceRight
are the least obvious of the iterative array methods. They should be used for algorithms that combine two values recursively in order to reduce a sequence down to a single value.
Using arrays to store other properties
Arrays can also be used like objects, to store related information.
const arr = [1, 2, 3];
arr.property = "value";
console.log(arr.property); // Logs "value"
Working with array-like objects
Some JavaScript objects, such as the NodeList
returned by document.getElementsByTagName()
or the arguments
object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. The arguments
object provides a length
attribute but does not implement the forEach()
method, for example.
Array methods cannot be called directly on array-like objects.
function printArguments() {
arguments.forEach(function(item) { // TypeError: arguments.forEach is not a function
console.log(item);
});
}
But you can call them indirectly using Function.prototype.call()
.
function printArguments() {
Array.prototype.forEach.call(arguments, function(item) {
console.log(item);
});
}
Array prototype methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays:
Array.prototype.forEach.call('a string', function(chr) {
console.log(chr)
})