Skip to main content

Command Palette

Search for a command to run...

Arrays in Javascript

What the heck are Arrays in JS?

Updated
•2 min read•View as Markdown
Arrays in Javascript

What is Arrays in javascript?

An Array is Data Structure which can store various data in it with one variable.

let myArray=[]
Array()

In javascript, index of array starts from 0

Properties of Array

1. length()

myarray=['ram','sita']
myarray.length() //2

Shows the length of the array

2. push()

myarray=['ram','sita']
myarray('laxman') //myarray=['ram','sita','laxman']

pushes the value in it to the end of the array

3. pop()

myarray=['ram','sita']
myarray.pop()  // myarray=['ram']

pops the last value from the array

4. shift()

myarray=['ram','sita']
myarray.shift() //myarray=['sita']

removes the first element from the array and returns the value

5. unshift()

myarray=['ram','sita']
myarray.unshift('laxman') //myarray=['laxman','ram','sita']

adds one or more elements in the array

6. map()

myarray=['ram','sita']
myarray.map(value=>console.log(value)) 
//ram
//sita

creates a new array with result of calling function on every element of the calling array

7. forEach()

myarray=['ram','sita']
myarray.forEach(element=>console.log(elements))
//ram
//sita

calls the function for each element in the array

8. concat()

myarray1=['ram','sita']
myarray2=['laxman']
myarray3=myarray1.concat(myarray2) // myarray3=[ 'ram', 'sita', 'laxman' ]

it merges two or more arrays

9. sort()

myarray=[ 'ram', 'sita', 'laxman' ]
myarray.sort() //[ 'laxman', 'ram', 'sita' ]

it sorts the array. default sorting value is ascending. it converts the elements into strings than compare the values of UTF-16 code to sort the array

10.indexOf

myarray=['ram','sita']
myarray.indexOf('ram'] // 0

Gives the value of the index in which given element is located in the array. it returns -1 when element is not found in the array