As we have learned, variables are used to store pieces of information. This makes it really easy for us as programmers to manipulate values.
For example, imagine we want to keep track of the amount of likes you have on an instagram photo.
1. We first want to make a variable with the current amount of likes...
let likes = 378;
2. Next, we want to increase likes by 3. We want to add three to the current value of likes so we add it as we normally would in a regular math expression.
In order to assign the new value of likes to the likes variable, we can simply reassign it. We do this by assigning the variable to an expression which includes itself.
In our example, we set the likes variable equal to itself + 3, so that likes' updated value is 381.
likes = likes + 3;
Imagine that we want to calculate how many likes we will have in x (x being some amount chosen by you) hours and for some reason we just can't do it in our heads and we want to write some code to do it for us.
We don't want to hard code values in for the average amount of likes because we want to allow our code to be user specific...how could we write this in code? Just like addition we can subtract, multiply, and divide variables.
1. We can first prompt the user for the average number of likes they get per hour.
let average = await promptNumber("Enter the average amount of likes you get on a pic in ONE hour:");
2. Next, we prompt the user for the number of hours they want to calculate.
let hours = await promptNumber("How many hours:");
3. We can now multiply by just using the variable names instead of their actual values
let love: number; love = average * hours;
Remember: the computer follows the same PEMDAS rules that we use in math.
love = (hours + 2) * average
is NOT the same as
love = (hours + average) * 2
Sometimes math and computers get a little weird and we get odd results from division. We use a tool called Math.floor(<the equation>). This helper function will round a number like 44.56 to 44.
For example,
let roundMe: number = Math.floor(124 / 33);
We assume that you have a solid foundation in algebraic problem solving! If you are concerned about your understanding of algebraic concepts, check out some Khan Academy tutorials or use the Message My Team function and reach out to your TAs about your concerns!