2.2 - Maths & Variables in JS
Part 1 - Maths
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.
Computers were designed to do mathematics quickly. Let's try!
+ and - for add and subtract
* and / for multiply and divide
== "is it equal" (that is important)
!= "is it not equal"
< > <= >=
** for exponent: 4**2 -> 16
Cannot assume BEDMAS - it is important to utilize brackets (or parentheses) ( ) properly!
Math.pow(base, exponent) // same as **
Task (Part 1)
Each math statement should be a new "console.log". For Example:
console.log(2 + 2); // will output 4
console.log(5 * 7.1); // 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