Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays.

Updated
•2 min read•View as Markdown
JavaScript Arrays.
E

Software Engineer

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.

V

Articles like this one really help me brush up on a particular topic I've lost touch with, good job!

1
E

Sure. Thanks

M

Nice

1
O

I like this spirit of trying to help others to learn more

1
E

Thanks buddy

E

Thanks buddy

C
Cy rus5y ago

Very informative

2
E

Sure, thanks.

1