Javascript Arrays

  • JavaScript Array is like an empty box that can be used to store different information.
  • It’s a temporary place to store many values.
  • Array is a piece of memory allocated to store a variety of information.
  • Arrays are defined using keyword var in JavaScript. You can assign any name to array, just like you can place any name on your empty box.
  • Arrays values are saved in a stack format.
  • Rules for naming arrays are similar to rule for naming variables.

Syntax for creating Arrays:

var NAME_OF_ARRAY = [“ARRAY VALUE 1”, “ARRAY VALUE 2”, “ARRAY VALUE 3”];

Another way to create an array is to use keyword let

let NAME_OF_ARRAY = [“ARRAY VALUE 1”, “ARRAY VALUE 2”, “ARRAY VALUE 3”];

  • var or let is keyword for creating array
  • NAME_OF_ARRAY can be any name of your choice.
  • The square brackets [ ] shows the multiple values of an array.
  • Array values are separated by commas
  • Array values can be text, html or a code.

Example of JavaScript Array

Another Syntax for creating Arrays:

var NAME_OF_ARRAY = new Array(“ARRAY VALUE 1”, “ARRAY VALUE 2”, “ARRAY VALUE 3”);

Another way to create an array is to use keyword let

letNAME_OF_ARRAY = new Array(“ARRAY VALUE 1”, “ARRAY VALUE 2”, “ARRAY VALUE 3”);

  • var or let is keyword for creating array
  • new is a constructor that can be used to create an Array
  • the word Array is also a keyword
  • NAME_OF_ARRAY can be any name of your choice.
  • The parenthesis ( ) shows the multiple values of an array.
  • Array values are separated by commas
  • Array values can be text, html or a code.

Example of JavaScript Array

  • In above example we have created an array called animals and then saved value cow on position zero, dog on position one and cat on position two.
  • In array values are stacked from position 0 to any position.
  • Each element gets a numeric index automatically assigned to it.
  • Indexes are start from zero.

The above example can also be coded in an another way

  • In above example we are using ArrayName[Value Position] syntax.
  • animals[0] represents the zero position of array

Some functions of Array

  • Use arrayName.length to access the number of elements in the array
  • Last element of the array has an index of arrayName.length -1
  • Arrays have many inbuilt functionalities like .pop(), .push(),.shift() etc

Rules for Naming Arrays

  • Variable names are case sensitive
  • Variable names cannot start with numbers
  • Variable names cannot contain spaces
  • Variable names can contain letters, numbers, $, _

How to read array values

document.write is one of the methods for retrieving values stored in an array.

Syntax for reading values of an array

document.write(ArrayName[Value Index]);

Example of reading values of an array