DEV Community

Cover image for Arrays in JS
Sakshi
Sakshi

Posted on

4 1

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay