1.2 - Variables & Math in JS
Part 1 - Maths
Computers were designed to do mathematics very quickly.
+ and - for add and subtract
* and / for multiply and divide
== "is it equal" (this is important)
Crucial note: a single equal sign '=' is not used for math in code! It means "become" or "assign"
!= "is it not equal"
< > <= >=
** for exponent: 4**2 -> 16
BEDMAS still applies - it is important to utilize brackets (or parentheses) ( ) properly
Math.pow(base, exponent) // same as **
Task (Part 1)
You don't necessarily need to use "console.log". For Example:
console.log(2 + 2); // this will output 4
5 * 7.1; // this will output 35.5
Practice some math. Have the computer calculate and output the correct answers to the following:
6 + 5
7 - 3
3 + 4 * 2
(4 / 2) + 3
5 + 2**3
Part 2 - Variables
Doing a quick calculation is easy. But what if we wanted to hold on to a value to be used later? Perhaps we want to hold a lot of values like a quadratic equation, the locations of items in a 3D space, a list of colours, phone numbers, or financials.
Variables talk directly to the memory in the computer. We reserve a block of space by asking for one, just like in math class:
Let w represent the number of watermelons
Let apple represent the number of apples
w = 2
apples = 7
Let shoppingList = w + apples
Q. In the example above, what is the value of "shoppingList"?
Please note - if you look online, you might see the keyword var being used instead of let. It is very important that, for the duration of this course, you always use let when creating a variable.
After the variable has been declared, you can use it as much as you want. Think of it like a box, bucket, or envelope.
For example, if we want to change the value of w to 4:
w = 4;
We did not use the keyword let again.
Note: You can declare a variable without giving it a value and set the value later.
Quadratic Formula Example:
Let's say you want to calculate the quadratic formula for 3x² + 7x - 9
Variables can be different types of data:
let myNumber = -45;
let myString = "Some text, in quotes";
let myBoolean = true; // or false
Can be combined (concatenated) using the '+' operator
myString = "This " + "that"; // the value is now 'This that'
Strings cannot be subtracted
myString = "This that" - "that"; // not possible
Anything with value is considered 'true'
let sample1 = 5; // considered true
let sample2 = 0; // considered false
let sample3; // considered false
Task (Part 2) in Replit
This task, along with many more examples of using maths & variables, is described in Replit (look for 1.2 - Maths & Variables).
Code is read and executed line-by-line, in the order you see/type it.
Do this first
Now do this
And now this
Code typically has numbers on each line so that we can easily talk-about and move-to specific areas more easily. If there is an error, the interpreter will give you the line number it thinks is the problem. For example, this error says the problem is on line 12: