Arrays are Objects
Notice that arrays are not on this list. This is because they are actually special objects. Check out the following pen to see for yourself:
This makes type checking for an array a bit tricky.
Array.isArray() should be used to be safe:
Arrays Copy by Reference
The fact that arrays are not primitive types has further implications. While primitives copy by value, objects copy by reference. See the following example:
After checking the console you will see that the
pets array and the
newPets array is the same despite all the changes being made on the
newPets array directly.
This is because when we made the assignment
var newPets = pets we did not create a new array. Instead, a new variable was created that points to the same array in memory.
If we want to make an actual copy of
pets then we need to make a new array and add the elements from the old array. One shortcut to achieve this is the
2D+ Arrays can be Tricky
slice() is a great way to copy 1D arrays, but what happens when using 2D arrays (an array of arrays)?
Once again, the operation will affect both arrays, although
grid === newGrid is returning false. This is because although we have created a new memory address for
newGrid, the elements that it contains still refer to the same memory address as the original! This is just a shallow copy, and in order to create a truly new array you need to perform a deep copy. Here is one way to do this:
In this example we know that
grid is a 3×3 2D array so we can setup a simple nested loop. Recursion would be a better method if we didn’t know the size beforehand.
By this point we know that arrays are objects and that they copy by reference, not value. Given this, it should come as no surprise that equality operations can be tricky as well:
As a human, I can see that
const is an ES6 spec keyword that, unlike
const works for arrays in the same way that it does for any other value, but it is important to remember how arrays work to avoid unwanted surprises. Take a look at the following code:
As you can see, declaring an array as a
const becoming available.