esra-justBI
1/24/2019 - 3:44 PM

Arrays

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

A way of makings lists, each item has a numbered position = index. Can store a combination of data types [].

Zero-index: positions start counting from 0 (first item: index = 0) Once you have access to an element in an array, you can update its value!

Even when arrays are declared as const, they remain mutable. The contents of a const array can be changed, but we cannot reassign a new array or a different value.

When we want to know how many elements are in an array, we can access the .length property.

.push() method adds items to the END of an array. Can take multiple arguments. It is a destructive array method, it changes the initial array. .pop() method removes the LAST item of an array. It does not take arguments. It returns the value of the last element, we can store this in a variable to be used for later. It mutates the initial array. There are a lot more array methods .join() [creates and returns a new string by concatenating all of the elements in the array] .slice() [shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.] .splice(pos, n), remove by index position (pos = index where to start, n = number of remove from that point) .shift() [removes the first from array] .unshift() [adds to beginning of array] .concat(). .indexOf() [find the index of a particular element, or -1 if not present]\

Pass-by-reference: If the array is mutated inside the function, that change will be maintained outside the function as well. We are passing the function is a reference to where the variable memory is stored and changing the memory.

Nested arrays: array contains another array.

['element example', 10, true]: consists of three elements

let cities = ['A', 'B', 'C'];
cities[0] = will access element at index 0: holds 'A'. 

const hello = 'Hello World';
console.log(hello[6]);
// Output: W

let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];

condiments[0] = 'Mayo';
console.log(condiments); //changes the first element

condiments = ['Mayo'];
console.log(condiments); //changes the entire array

const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];

utensils[3] = 'Spoon';
console.log(utensils); //changes the last element

utensils = 'Spoon';
console.log(utensils); //error not possible to re-assign const array

//.pop() method
const newItemTracker = ['item 0', 'item 1', 'item 2'];

const removed = newItemTracker.pop();

console.log(newItemTracker); 
// Output: [ 'item 0', 'item 1' ]
console.log(removed);
// Output: item 2

//nested arrays
const nestedArr = [[1], [2,3]];
console.log(nestedArr[1]); //output [2,3]
console.log(nestedArr[1][0]); //output 2

array.splic(p, n, 'xxx') //replaces with xxx
console.log(array.join(' ')); //makes a string with all spaces in between