Arrays in JavaScript

We can define arrays in 2 ways.

  1. using new Array() constructor
  2. Using array literals []

Below example shows how to create arrays using “Array” Constructor.

var cities = new Array(“Brisbane”,”Perth”);

Below examples illustrates how to work with literal Arrays in JavaScript.

//We can create arrays using below syntax.
var cities = [ “Brisbane”, “Sydney”, “Perth” ];
console.log(“Current Array Elements -> ” + cities.join())

//Show the first element in array
console.log(“First element in array -> ” + cities[0])

//Find the length of array
console.log(“Length of the array -> ” + cities.length)

//Arrays in JavaScript are dynamic
//Increasing the size of Array
cities[6] = “London”

//Find the new length of array. Length should be 7
console.log(“Length of the array -> ” + cities.length)

//Show the sixth element in array
console.log(“Sixth element in array -> ” + cities[6])
//Show the fourth element in array
console.log(“Fourth element in array -> ” + cities[4])

//Decreasing the size of Array
cities.length =3

//Show the sixth element in array…It will be undefined
console.log(“Sixth element in array -> ” + cities[6])

//Arrays are objects. So we can create new properties for the array
cities.myprop = “p1”
console.log(“Value of New property of array -> ” + cities.myprop)

//To check if element exists at specific index, we can use below syntax
console.log(“Is there an element -> ” + (5 in cities))

cities = [ “Brisbame”, “Sydney”, “Perth” ];
console.log(“Current Array Elements -> ” + cities.join())

//Prepending and Appending Elements in Array

console.log(“Prepending Munich in Array -> ” + cities.unshift(“Munich”))
console.log(“Array Elements after prepend operation-> ” + cities.join())

console.log(“Appending Rio in Array -> ” + cities.push(“Rio”))
console.log(“Array Elements after append operation-> ” + cities.join())

//Remove first and last element in array
console.log(“Removing first element in Array -> ” + cities.shift())
console.log(“Array Elements after removing first element-> ” + cities.join())

console.log(“Removing last element in Array -> ” + cities.pop())
console.log(“Array Elements after removing last element-> ” + cities.join())

//Finding the index of an element in array
console.log(“Index of Sydney in Array -> ” + cities.indexOf(“Sydney”))
//Joining elements by character
console.log(“Joining elements by * -> ” + cities.join(“*”))

//Slicing first element in array
console.log(“Slicing first element in Array -> ” + cities.slice(1))

You may also like...