Often, we want to update the value of a variable and immediately reassign the same variable to that updated value
eg:
let heads = 1; let tails = 2; if (landedHeads) { heads = heads + 1; } else { tails = tails + 1'
Is there a faster way we could do this?
There is!
We have a variety of 'shortcuts' to allow us to reassign variables without typing the variable twice.
x = x + 7; // becomes x += 7; x = x - 7; // becomes x -= 7; x = x * 7; // becomes x *= 7; x = x / 7; // becomes x /= 7;
There are 3 ways we can add or subtract 1 from a variable
i = i + 1; //addition i = i - 1; //subtraction
i += 1; //addition i -= 1; //subtraction
i++; //adds 1 to the current value of i and stores it back into 1 i--; //subtracts 1 from the current value of i and stores it back into 1
Where could we use this?
Loops are a great place to use these shortcuts, as they usually involve incrementing a counter variable.
let i = 0; while (i < 5) { if (i * 2 < 6) { print("Hello"); } else { print("World"); } i++; }
What would the output of the above code be? What would i's value be each time the loop runs?