Basic Array Operations in JavaScript

Basic Array Operations in JavaScript

Arrays.js

ยท

2 min read

Arrays Defintion

Arrays are list-like objects whose prototype has methods to perform traversal and mutation (the action or process of changing) operations. The length of a JavaScript array nor the types of its elements are fixed.

An array is a special type of variable, which can store multiple values. Each value is associated with numeric index starting with 0.

Create an array

// these are the two ways to create an empty array
let emotions = new Array();
let emotions = [];
// we add items to the array
let emotions = ['๐Ÿ˜€', '๐Ÿ˜‚']

console.log(emotions.length)
//2

Access an Array item by using its index position

let first = emotions[0]
// '๐Ÿ˜€'

let last = emotions[emotions.length - 1]
// '๐Ÿ˜‚'

Loop over the array

emotions.forEach(function(item, index, array) {
  console.log(item, index)
})
// '๐Ÿ˜€' 0
// '๐Ÿ˜‚' 1

Add an item to the end of an Array

let newLength = emotions.push('๐Ÿฅฐ')
// ['๐Ÿ˜€', '๐Ÿ˜‚', '๐Ÿฅฐ']

Remove an item from the end of an Array

let last = emotions.pop() // remove ๐Ÿฅฐ (from the end)
// ['๐Ÿ˜€', '๐Ÿ˜‚']

Remove an item from the beginning of an Array

let first = emotions.shift() // remove ๐Ÿ˜€ from the front
// ['๐Ÿ˜‚']

Find the index of an item in the Array

emotions.push('๐Ÿฅณ')
// ['๐Ÿ˜€', '๐Ÿ˜‚', '๐Ÿฅณ']

let pos = emotions.indexOf('๐Ÿ˜‚')
// 1

Learn more about Arrays here ๐Ÿ‘‡๐Ÿพ

Thanks for reading ๐Ÿ†