JavaScript Arrays.

JavaScript Arrays.

Arrays are one of the commonly used data structures in the field of computer science. They are mainly used for mutation operations. example:

let marks=[20, 40, 50, 60];

Arrays can also contain items that are of different data types. For example this array:

let studentDetails = [20, 'Mike Collins', 'Third year']

contains both numbers and strings.

There are two main ways of accessing array items.

  • The Dot Notation.

  • Bracket Notation

This article talks about arrays and common array operations.

Common Operations

Create an array

let programmingLanguages = ['JavaScript', 'Java', 'Python', 'Ruby', 'PHP'];

Find the length of array

console.log(programmingLanguages.length);
// 5

Accessing an array items using the index:

let firstLanguage = programmingLanguages[0];
//JavaScript

Find the last item in an array

let lastLanguage = programmingLanguages[programmingLanguages.length - 1]
//PHP

Loop over an Array

programmingLanguages.forEach((language) =>{
console.log(language);
//JavaScript
//Java
//Python
//Ruby
//PHP
});

Add an item to the end of an Array

programmingLanguages.push('Go');
console.log(programmingLanguages);
//['JavaScript', 'Java', 'Python', 'Ruby', 'PHP', 'Go']

Remove an item from the end of an Array

programmingLanguages.pop();
console.log(programmingLanguages);
//['JavaScript', 'Java', 'Python', 'Ruby', 'PHP']

Remove an item from the beginning of an Array

programmingLanguages.shift();
console.log(programmingLanguages);
//['Java', 'Python', 'Ruby', 'PHP']

Add an item to the beginning of an Array

programmingLanguages.unShift('Go');
console.log(programmingLanguages);
//['Go', 'Java', 'Python', 'Ruby', 'PHP']

Find the index of an item in the Array

programmingLanguages.indexOf('Python');
//2

Remove an item by index position

let removedLanguage = programmingLanguages.splice(pos, 1);
console.log(removedLanguage);
//Java

Copy an Array

let arrayCopy = programmingLanguages.slice()

This article was target towards helping beginners to get started with arrays and common array operations.

Find a more detailed explanation on arrays here: MDN

Thank you for reading.