DEV Community

Cover image for Arrays in JS
Sakshi
Sakshi

Posted on

Arrays in JS

Array

An array organizes items sequentially, one after another in memory.

Syntax

const array_name = [item1, item2, ...];   
Enter fullscreen mode Exit fullscreen mode

Each position in the array has an index, starting at 0.

Strengths:

Fast lookups.
Retrieving the element at a given index takes O(1)O(1) time, regardless of the length of the array.

Fast appends.
Adding a new element at the end of the array takes O(1)O(1) time, if the array has space.

Weaknesses:

Fixed size.
You need to specify how many elements you're going to store in your array ahead of time. (Unless you're using a fancy dynamic array.)

Costly inserts and deletes.
You have to "scoot over" the other elements to fill in or close gaps, which takes worst-case O(n)O(n) time.

Some languages (including Javascript) don't have these bare-bones arrays.

const cars = ["Saab", "Volvo", "BMW"];

//or

const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";

//or

const cars = new Array("Saab", "Volvo", "BMW");

Enter fullscreen mode Exit fullscreen mode

STAY TUNED FOR NEXT BLOG, HOPEFULLY IT WILL LONGER THAN THIS xD

Thanks for reading <3

Top comments (0)