DEV Community

Veronica
Veronica

Posted on

Heart Eyes for Array Methods

It's been almost three months (aka half-way there!) into my first intensive experience in a coding boot camp, and it's clear that objects and arrays are pretty important to even a novice at JavaScript. Objects are key-value pairs (like a word and its corresponding definition in a dictionary) while an array, which is a special type of object, is an ordered list, which is useful when dealing with a large amount of the same type of data, like a collection of names.

For example, an array of random colors is noted such as:

let colors = ['yellow', 'black', ‘blue’, ‘green’]
Enter fullscreen mode Exit fullscreen mode

With arrays, JavaScript gives you the ability to make basic edits like add, delete, and update the data as well as helps you sort through the information with limited amounts of code. These are called array methods. There is a plethora of these cool little mechanisms, not even a fraction of which I have tried and tested myself yet, but here are a couple of my favorites so far.

Push
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

Enter fullscreen mode Exit fullscreen mode

Splice
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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

Collapse
 
cheston profile image
Cheston

Concise explanations!
Always helpful to hear others explain code in their own words.
Happy first post! 👍🏻

Collapse
 
veronicorn profile image
Veronica

Thanks so much, Cheston!