So, in the last entry, we looked at the slice() function and explained how it worked and what it’s arguments were for. Today, we’re going to look at some more advanced examples, courtesy of MDN.
“But,” you ask, “why do you keep using MDN’s examples? Why not make your own? Surely MDN explains it well enough?”
Well, maybe. And for some people, especially those who have been coding in other languages for years, I’m sure that I’m kind of beating this into the ground. But, for those who haven’t, or want to really get the principles, I figure thinking through MDN’s examples in detail really helps. At least, it does for me, and I do my best thinking on paper, so here we are.
All right, let’s look at a more advanced example, using an object instead of just an array. We’ll declare our variables first.
Note that myHonda is an Object, and myCar is an array. We’re creating a new array called newCar by using the slice function to get elements 0 and 1 (not 2 – remember, the end parameter is NOT included in the “slice”) of myCar. That would, of course, be myHonda (which is an object) and 2.
I removed the toSource() arguments in the original MDN, which are used here to send the results to the screen and aren’t really needed for what we’re explaining, plus they’re confusing. So what we’ll get as output is:
Now, the thing to note here is, since we are using an object reference, is that myCar is the object myHonda, and the color attribute of myHonda is red. We sliced myCar’s first two elements into newCar, and so newCar is myHonda, and of course its color attribute is also red.
We can change things up a bit and make the car a different color:
The output is:
The new color of my Honda is purple
Now note that we changed the color in myHonda to be purple rather than red. How will that change our output? Let’s find out!
For output we get:
myHonda is referenced by both myCar AND newCar, so of course we get purple instead of red, because we changed the original object and not a copy.
And that’s the slice() function in action! Next, we’ll look at an actual by golly algorithm challenge from FreeCodeCamp to try and tie all of this together, before attempting to solve my original task of Symmetric Difference!