Arrays object and methods

Arrays – It is an ordered collection of values with each value is called an element, having a numeric position in the array called its index. JavaScript arrays may be of any type and elements of the same array can be of different types.

Array creation – An array is created with a comma-separated list of elements within square brackets. Array can be empty with no elements or with elements as

var blank = []; // Empty array

var odd = [1, 3, 5, 7]; // Array with elements

Array object – Another way to create an array is with the Array() constructor by calling it with

  • No arguments: var a = new Array();
  • A single numeric argument, of length: var a = new Array(10);
  • Two or more elements: var a = new Array(5, 4, 3, 2, 1, “testing, testing”);

Element access – To access an element of array use the [] operator with array name and index in the square brackets as arrayname[index]. This form can be used to read or write value at the specified index.

Array methods – Various array methods are discussed below:

  • concat(array1 [, array2 [, …]]) –     Creates a new array by joining two or more arrays
  • filter(callback [, contextObject]) –     Filters the elements of an array using a callback function
  • join([separator]) –     Join the elements of the array into a string using a separator
  • pop() –     Removes the last element of the array and returns that element
  • push(element0 [, element1 [, …]]) –     Appends one or more elements to the end of the array and returns the new length of the array
  • reduce(callback [, initialValue]) –     Reduce the array to a single value using a callback function from left-to-right
  • reverse() –     Reverses the order of the elements in the array
  • shift() –     Removes the first element of the array and returns that element
  • slice(offset [, length]) –     Extracts a section of the array and returns a new array containing the extracted elements
  • sort([compare_function]) –     Sorts the array optionally using a callback function
  • splice(offset , length [, element1 [, element2 [, …]]]) –     Replaces elements from the array with something else
  • toString() –     Returns a string representation of the array
  • unshift(element0 [, element1 [, …]]) –     Prepend one or more elements to the front of the array and returns the new length of the array
  • valueOf() –     Returns the primitive value of the array

Back to Tutorial

Share this post
[social_warfare]
Capture and release events
String object, methods and regular expression

Get industry recognized certification – Contact us

keyboard_arrow_up