Pokemon Array

scroll down

Let's say you have an array of pokemon elements

let pokemon = ["alakazam", "onix", "squirtle", "snorlax"]

[
,
,
,
]

Let's say I want to see one of the elements in the pokemon array I will call it based on what index number it is. In the javascript worled everything starts at 0, NOT 1

Index#
0
1
2
3
[
,
,
,
]

pokemon[0] is "alakazam"

pokemon[3] is "snorlax"

Now we want to add psyduck to our group. You can add an element to the end of the array with push()

pokemon.push("psyduck")

the pokemon array will look like this: ["alakazam", "onix", "squirtle", "snorlax", "psyduck"]

[
,
,
,
,
,
]

We realized we actually don't want psyduck and since he's on the end of our array we can pop him out. (Yes like a zit, you pop it!)

pokemon.pop()

the array will now look like this: ["alakazam", "onix", "squirtle", "snorlax"]

[
,
,
,
]

Now let's say we don't want alakazam anymore in our array, we can shift the array to pop out the first element from our pokemon array

pokemon.shift()

the array will now look like this: ["onix", "squirtle", "snorlax"]

[
,
,
]

Now let's say we want pikachu to be the first element of our array, we can unshift the array.

pokemon.unshift("pikachu")

the array will now look like this: ["pikachu", "onix", "squirtle", "snorlax"]

[
,
,
,
]

Splice vs Slice

With both of these array methods you can remove items, but there is a difference in performance.

The splice() method returns the removed item(s) in an array. You can use this also to add items into an array

slice() method returns the selected element(s) in an array, as a new array object

Splice can be used to remove and add items into an array.

splice(start, deleteCount, item1)

Now let's say we want another pokemon to be the after the onix in our array, we can use the array and add where add the index number where we want to put our element.

pokemon.splice( 2, 0,"meowth")

the array will now look like this: ["pikachu", "onix", "meowth","squirtle", "snorlax"]

[
,
,
,
,
]

Slice

Slice does not alter the original array. It returns a shallow copy of elements from the original array. Slice is used like this

slice(start, end)

Let's use slice to cut out some pokemon.

let newPokemon = pokemon.slice(1, 3)

new pokemon will bring back: ["onix", "meowth"]

[
,
,
]

while pokemon will bring back ["pikachu", "onix", "meowth","squirtle", "snorlax"]

[
,
,
,
,
]

Back to the top