DevNotes

DevNotes

@devnotes ·

JavaScript Part 6: Arrays

An array is an ordered list of values, like the items in a cart. You'll use arrays more than anything else in JavaScript.

Making one and reading it

JavaScript
const fruits = ["mango", "banana", "apple"];
fruits[0]                  // "mango"fruits[2]                  // "apple"fruits.length              // 3fruits[fruits.length - 1]  // "apple", the last one

Positions, called indexes, start at 0, not 1. That's why the last item is at length - 1. Asking for an index that doesn't exist, like fruits[10], gives undefined rather than an error.

Changing it

JavaScript
fruits.push("guava");    // add to the endfruits.pop();            // remove from the endfruits.unshift("kiwi");  // add to the startfruits.shift();          // remove from the startfruits[1] = "papaya";    // replace one item

All of this works even though fruits is a const. const stops the name from pointing at a different array, but the array itself can still change.

Finding things

JavaScript
fruits.includes("mango")  // truefruits.indexOf("apple")   // 2, or -1 if it isn't there

The big three: map, filter, find

These take a function and run it on every item. They replace most of the loops you'd otherwise write by hand.

JavaScript
const prices = [100, 250, 40, 600];
const withDelivery = prices.map((p) => p + 20);// [120, 270, 60, 620]
const cheap = prices.filter((p) => p < 200);// [100, 40]
const firstBig = prices.find((p) => p > 200);// 250
  • map makes a new array with every item changed by your function. Same length, new values.
  • filter makes a new array holding only the items your function says yes to.
  • find gives you the first item that matches, or undefined if none do.

None of them touch the original. prices is still [100, 250, 40, 600].

To add everything up, reduce carries a running total along the array:

JavaScript
const total = prices.reduce((sum, p) => sum + p, 0);  // 990

The 0 at the end is where the total starts.

Sorting has a trap

JavaScript
[10, 1, 5, 100].sort();                 // [1, 10, 100, 5][10, 1, 5, 100].sort((a, b) => a - b);  // [1, 5, 10, 100]

By default, sort compares items as text, so "100" comes before "5", the same way "apple" comes before "banana". For numbers, always pass the comparison. Also, unlike map and filter, sort changes the original array.

Chaining

map and filter both return arrays, so you can chain them:

JavaScript
const labels = prices  .filter((p) => p >= 100)  .map((p) => `Rs ${p}`);// ["Rs 100", "Rs 250", "Rs 600"]

You'll write a lot of code like this in React, turning data into what shows on the screen.

Try it

Start with const marks = [45, 82, 67, 91, 38, 74];. Use filter to keep the passing marks (40 and above), map to add 5 bonus marks to each, and reduce to add them up so you can work out the average.


Next: JavaScript Part 7: Objects

javascriptwebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.