HomeToolsAbout a20k

Array Basics

Purpose

Array is used to assign multiple values to a single variable

const x = ["element1", "element2"]; // empty array is also a legit array const emptyArray = []; // empty element is initialized as `undefined` console.log(emptyArray[0]); // undefined

Zero-indexed

Arrays (in JS) are zero-indexed

  • Meaning the element count/position starts at 0 instead of 1
const arr = [1,2,3]; // accessing first array element arr[0]; // 1 // accessing last array element arr[arr.length - 1]; // 3

Initialization/Creation

// basic initialization const arr1 = [item1, item2, item3]; const arr2 = new Array('item1','item2','item3'); // Create n-length `null` values filled array const nullArr = new Array(n).fill(null); // fill with x number of 0s const prefilledArr = Array(x).fill(0); // faster initialization with `undefined` fills const arr = []; arr.length = n;

Naming Conventions

Array name should be plural

Let's say there is a collection of frogs in an array

["red frog", "happy frog", "green frog"];

If we name the array as frog, then we have a list (multiple frogs) assigned to a singular variable name

  • This does not accurately represent what the variable contains
/* incorrect */ // singular frog const frog = ["red frog", "happy frog", "green frog"]; /* correct */ // multiple frogs in variable frogs const frogs = ["red frog", "happy frog", "green frog"]; // single frog in variable frog const frog = "happy frog";

Overriding Element

// changing value at index position 0 arr[0] = "different-element-1";

Arrays can be nested

const arrOfArr = [["iq", "ag", "bc"], ["ef", "hi"]]; arrOfArr[1] // ["ef", "hi"] arrOfArr[1][1] // "hi"

Adding/Removing Elements

// adding element arr.push('new_item') // adds to end of arr arr.unshift('new_item') // adds to start of arr // removing element arr.pop() // removing element from the end of array arr.shift() // removing element from the start of arrays

Iteration

// Iteration using `for` loop const arr = [ '0', '1', '2' ]; function call_me(params) { for (i=0; i<params.length; i++) { console.log(params[i]); } } call_me(arr); // '0', '1', '2' // Iteration using `for...of` const wordArr = ['i', 'have', 'some', 'stings', 'inside', 'me']; for (let value of wordArr){ console.log(value); } // 'i', 'have', 'some', 'stings', 'inside', 'me'
© VincentVanKoh