For example, an array of random colors is noted such as:
let colors = ['yellow', 'black', ‘blue’, ‘green’]
Adds new element to the end of an array
let colors = ['yellow', 'black', ‘blue’, ‘green’] colors.push('white'); alert(colors) // Output will be yellow, black, blue, green, white
Deletes item(s) from an array, from any location. The parameters you pass through indicate where in the array you’re beginning and how many items to remove. Remember the index rule: the first item in an array is defined as 0, second item is 1, third item is 2, and so on.
let colors = ['yellow', 'black', ‘blue’, ‘green’, 'white'] // let’s remove black and blue out of there! colors.splice(1, 2) // so starting at index 1 (black), remove 2 items (black, blue) alert(colors) // Output will now be yellow, green, white
Splice is doubly cool because not only can you delete items from anywhere in the array, you can also insert new items at the same time.
let colors = ['yellow', 'black', 'blue', 'green', 'white'] // let’s remove blue and green and add a bit more flair colors.splice(2, 2, 'rose gold') alert(colors) // Output will be yellow, black, rose gold, white
I hope to put to use and get to know many more of these tiny heroes (many of which you can find here) throughout my boot camp journey and beyond. Hooray for arrays!