Let’s say we create an application that will keep count of how many popsicles you have in the fridge. We will store this in a variable for easy access:
let popsicles = 5
This morning a friend came over and gave you a popsicle for some random reason. We want to add this to our popsicle count so:
popsicles = popsicles + 1
Or in other words we are taking all the popsicles from the package or variable
popsicles and adding another into it, and then putting all six back into the box. popsicles
will be equal to 6. Because this is such a common application in programming, we have a shortcut to adding one to a number:
popsicles++;
// exactly the same as doing
popsicles = popsicles + 1
Now let’s do the opposite. You come in from working outside and decide to have a popsicle, so you pull one out of the box. We can do so like this:
console.log('popsicles') // 5
popsicles = popsicles - 1;
In this operation we take our entire package of popsicles (5) and subtract one from it. You might be wondering why we have to do
popsicles = popsicles - 1;
instead of just
popsicles - 1;
popsicles - 1
gives us a value, it is not a variable. Think about our example. We grab all the popsicles out of our box of popsicles which has 5 in it, so we now have 5 popsicles in our hand. We then remove one of these popsicles leaving us with 4 popsicles. We don’t have a use for these 4 popsicles, so we put them back in the box. In this example:
popsicles = popsicles - 1
we grab the variable, remove 1 popsicle from it, and put the other 4 back into the box called popsicles. If we just remove one from it without doing anything, it does us no good.
let popsicles = 5;
popsicles - 1;
console.log(popsicles) // 5
This is because popsicles is still 5 because we gave it that value. We need to update the value by assigning it a new value. We get this new value and then assign it.
let popsicles = 5;
popsicles = popsicles - 1; // or popsicles--;
console.log(popsicles) // 4
We must assign the value to the variable to use it later. Because it would be convenient to just write popsicles - 1
, because it does not do what we want, we have a shortcut that will assign it for us in popsicles--
. Hope this helps clarify things.