Bootcamp

From idea to product, one lesson at a time. To submit your story: https://tinyurl.com/bootspub1

Follow publication

JavaScript Arrays: Tips, Tricks and Examples

Exploring popular JS Array methods with sample code

Digital Plumbers
Bootcamp
Published in
5 min readJul 27, 2023

--

An array, in JavaScript, is like a super-powered list. It’s a single variable used to store different elements. It’s like a chest of drawers where you store your socks, undies, and that ugly Christmas sweater your aunt knitted for you (Sorry aunt Debbie).

Arrays contain two principle components: Elements, the stuff in your drawers, and the index, or the numerical representation of that drawer relative to the dresser/other collection of drawers. Important!!! In case you are totally unfamiliar with javascript arrays, the index begins at 0, meaning an array of 5 items will have a maximum index of 4.

Courtesy of https://www.tutorialstonight.com/js/js-array

Here are some quick array examples:

//empty
[]
//strings
[‘thanks’, ‘for’, ‘reading’, ‘and’, ‘sharing!’]
//integers
[2, 4, 6, 8, 10]
//variables
let user = 'tony';
let userInput = 'hello';
let userStatus = 'online';
[user, userInput, userStatus]

Arrays are incredibly versatile. They can hold anything from numbers and strings to objects and other arrays (we call those ‘nested’ arrays, like Russian dolls of code). But the real power of arrays comes from the array methods JavaScript provides. These are built-in functions that allow us to manipulate arrays in various ways — think of them as your array Swiss Army knife.

Buckle up, grab your favorite caffeinated beverage, and let’s get this party started.

1. forEach(): The Social Butterfly

The forEach() method is like that friend who insists on personally greeting everyone at the party. It visits each element in your array, one by one, and performs a function. No element is left unattended.

let partyGuests = [‘Bob’, ‘Sue’, ‘Jim’, ‘Ann’];
partyGuests.forEach(guest => console.log(`Hello, ${guest}!`));

2. map(): The Artist

The map() method is the artist of the group. It takes your array and transforms it into something new, like a sculptor turning a block of marble into a masterpiece.

let numbers = [1, 2, 3, 4];
let squares = numbers.map(num => num * num)…

--

--

Bootcamp
Bootcamp

Published in Bootcamp

From idea to product, one lesson at a time. To submit your story: https://tinyurl.com/bootspub1

Digital Plumbers
Digital Plumbers

Written by Digital Plumbers

Software consultancy and development done right | digitalplumbers.io

No responses yet

Write a response