arrays methods

PHOTO EMBED

Wed Jul 13 2022 18:27:34 GMT+0000 (Coordinated Universal Time)

Saved by @cruz #javascript

//with arrays it is always 1 extra from 0
//.push adds to end of array
const chores = ['wash dishes', 'do laundry', 'take out trash'];


chores.push('item 3', 'item 4');

console.log(chores);

////.pop removes the last

const chores = ['wash dishes', 'do laundry', 'take out trash', 'cook dinner', 'mop floor'];


chores.pop();
console.log(chores);

///.shift removes the first
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];

groceryList.shift();
console.log(groceryList);

///.unshift adds to beginning of array

groceryList.unshift('popcorn');
console.log(groceryList);

//use .slice to select items and copy in an array. for example .slice(1,4) means 1-4.
// use .splice to actually select and change the array and replace it with a new string see secret message excerise for better explanation.

console.log(groceryList.slice(1,4));

groceryList.splice(1,4);

// .indexOf allows you to select a particular item

const pastaIndex = groceryList.indexOf('pasta');
console.log(pastaIndex);
///when you pass an array into a function, if the array is mutated inside the function, that change will be maintained outside the function as well. You might also see this concept explained as pass-by-reference since what we’re actually passing to the function is a reference to where the variable memory is stored and changing the memory.


const concept = ['arrays', 'can', 'be', 'mutated'];

function changeArr(arr){
  arr[3] = 'MUTATED';
}

changeArr(concept);

console.log(concept);

function removeElement(newArr){
  newArr.pop();
}

removeElement(concept);
console.log(concept);
content_copyCOPY