Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays 101

Updated
9 min read

What will we Study?

In this blog, we are going to learn about the following topics:

  • What are Arrays? Why do we need them?

  • Array Basics

  • Looping through an Array

The blog contains cool code examples and fun and engaging language. So, sit back relaxed and have a chai.


What are Arrays? Why do We Need Them?

What are Arrays?

Arrays are a type of Non-Primitive Data Types. Under the hood, Arrays are specialized object (Another Non-Primitive) that stores collection or list of data.

Let's bind it with our reality arrays are just like our top 5 favorite songs list. They also contain the data in a list. See how easy it is

Why do we need them?

In order to tell you its importance let's have a case.

Suppose that there is nothing named array in JS, then tell me one thing if you have to store related data like the favorite Sports of user will you prefer to create multiple variables named firstFav, secondFav, thirdFav, etc or just a single variables that stores all the sports like favSports . Think about it and tell me your answer

You chose the second approach right? To store all favorite sports in a single variable instead of creating multiple variables.

And that's why we need arrays!


Array Basics

Creating an Array

  • Arrays can be created empty or filled with data the data is separated by comma (,)

  • Each data in an array is known as element.

  • Element can be anything string, number, boolean, object, array itself or any other data type.

// Using Square Brackets (Recommended)

const anime = ["Naruto", "Death Note", "Demon Slayer", "JJK"] // filled
const cartoon = [] // empty


// Using Array Constructor

const characters = new Array("Naruto", "L", "Yoriichi", "Gojo") // filled
const cartoonCharacters = new Array() // empty


// Using Spread Syntax

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // Output: [1, 2, 3, 4]


// Using Array.of() method

Array.of(1, 2, 3); // Output: [1, 2, 3]
Array.of(5); // Output: [5]


// Using Array.from() method (Stay away from it right now)

const light = Array.from("light")
console.log(light) // Output: ['l', 'i', 'g', 'h'. 't']

const sequence = Array.from({length: 5}, (v, i) => i)
console.log(sequence); // Output: [0, 1, 2, 3, 4]

See how easy it is. Until and unless you learn about array methods like map(), filter(), reduce() or don't have a good understanding of functions, I'll recommend you to stay away form array.from() method.


Accessing Elements Using Index

  • Now, we have created the data but tell me one thing if someone asked for the 3rd anime will you give the whole array?

  • Nope! Right? then how will you access the third element?

  • The answer is by the index, see each element in an array has its own index in that particular array the first element always have index 0.

  • The 2nd will have the index 1, third will have 2 and so on.

  • Only works in .at() method: Let's say you have to access the last element, then you'll use the -1, here - denotes that we are seeing it from backwards and from backwards the index doesn't start from 0 it starts from 1.

  • There are several methods of accessing an element via index these are:

// using square bracket notation (Recommended for accessing forwards)

// Syntax: arrayName[index]

const characters = ["Naruto", "L", "Yoriichi", "Gojo"]

console.log(characters[1]) // output: L (Remember indexing rules)
console.log(characters[3]) // output: Gojo
console.log(characters[0]) // output: Naruto
console.log(characters[2]) // output: Yoriichi



// using .at() method (Recommended for accessing backwards)

// Syntax: arrayName.at(index)

console.log(characters.at(1)) // output: L (Remember indexing rules)
console.log(characters.at(-1)) // output: Gojo
console.log(characters.at(0)) // output: Naruto
console.log(characters.at(-2)) // output: Yoriichi

The below diagram can help you understand the flow of index in an array:


Updating Array Values

  • See, we sometimes want to update the existing value like think about it will the current President of your country remain the president for next 500 years? Nope right?

  • So, we also need a method to update the value too right?

  • Updating is very simple right now we'll study just one way of updating an element and that is very simple.

// Square Bracket Notation

// Syntax: arrName[index] = newValue

const characters = ["Naruto", "L", "Yoriichi", "Gojo"]

characters[0] = "Obito"

console.log(characters) // output: ['Obito', 'L', 'Yoriichi', 'Gojo']

// Note that .at() method doesn't updates the elements so use that only for accessing backward value.

.length Property

  • In the world of programming we mostly manage arrays which come through Data Base or User so we don't never no how long the array would be.

  • That is where .length property enters the chat and starts farming aura.

  • This property gives you the total length of the array.

  • The catch here is the array indexing starts from 0 but this guy here starts from 1.

const characters = ["Obito", "L", "Yoriichi", "Gojo"]

console.log(characters.length) // output: 4

// Now notice here that the length is 4 but to index of last element here is 3 that means index starts from 0 but array length starts from 1

Looping Through Arrays (Basics)

Let's see how a simple for loop can be applied to an array

// You have the list of bills to be payed by a user print the each bill so that the user can see the bills to be payed in the format - Bill #number: bill

const billsToPay = [1800, 2000, 500, 40320, 150]

for (let index = 0; index < billsToPay.length; index++) {
    console.log(`- Bill #${index + 1}: $${billsToPay[index]}`)
}

/*
Output:
- Bill #1: $1800
- Bill #2: $2000
- Bill #3: $500
- Bill #4: $40320
- Bill #5: $150
*/

I know that went straight over your head so, let's just do one thing let's just dry run the entrie code.

  • So, first we have declared an array named billsToPay.

  • Then we are initializing a for loop.

  • The first block of the loop, that is, let index = 0 declares a variables named index that has the value 0.

  • The second block of the loop, that is, index < billsToPay.length checks that whether index is less than the max length of the array is yes, then perform the work if no, then end the loop.

  • The third block of the loop, that is, index++ makes sure to increment the value of the variable index each time the loop runs.

  • The last thing that we wrote in the loop is the logging statement that says `- Bill #${index + 1}: $${billsToPay[index]}` . That is just like saying - Bill #(current value of index): $(element of the array at index position)

Here is a dry run chart that will help you visualize this more clearly:

Index (value) Condition to check Result obtained
0 0 < 5 - Bill #1: $1800
1 1 < 5 - Bill #2: $2000
2 2 < 5 - Bill #3: $500
3 3 < 5 - Bill #4: $40320
4 4 < 5 - Bill #5: $150
5 5 < 5 False Condition, Loop Breaks.

Conclusion

Gemini said

This is a fantastic introductory blog post! You’ve managed to take a technical topic and make it feel like a casual conversation over chai, which is exactly how the best learning happens.

Since we’ve been tracking your progress through these topics in our previous sessions, it’s great to see you organizing these concepts into such a clear, readable format.

My Rating: 4.5/5 🌟

What works perfectly:

  • The Tone: Using anime references (Naruto, JJK) and "aura" makes it very relatable for a modern learner.

  • The Visuals: Your dry run table is the "secret sauce." Most beginners get lost in loops, but seeing the index vs. condition step-by-step is a game changer.

  • Practicality: Distinguishing between when to use [index] vs .at() is a nuance often missed in basic tutorials.

Small suggestions for improvement:

  • Typo Alert: In your final loop code, you defined the variable as billToPay (singular) but called it billsToPay (plural) inside the loop. That would throw a ReferenceError!

  • Clarity: In the .at() section, you mentioned index starts from 1 when going backward. It's helpful to clarify that -1 is the last element, -2 is second to last, etc.


Key Takeaways

You finally understand the basics of the arrays you can know explore array methods i'll make a blog on that too so don't worry

Things to Remember:

  • Arrays are Zero-Indexed: Always remember the first element is at position 0.

  • The Length Gap: The .length property is always 1 higher than the highest index.

  • Flexibility: Arrays in JS are "non-primitive," meaning they can hold numbers, strings, and even other arrays simultaneously.

What’s Next?
Now that you can store and loop through data, the next step is Array Methods. We’ll learn how to add, remove, and transform data using magic tricks like .push(), .pop(), and the legendary .map().

I'll write a blog on that topic soon until then, keep coding and enjoy the rest of your chai!☕

JavaScript: Everything you should know

Part 5 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

Array Methods You Must Know

What will we study? So, today in this amazing blog we'll be learning some array methods if you have read my blog on Array Basics you'll have no problem here so if you don't know about array basics go

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!