1.2 - Variables & Math in JS


Web browsers can run a scripting language called JavaScript. The syntax is very similar to C, C++, C#, Java, etc...

Yesterday we learned about something called the console.

Today's Lesson: 1.2 - Maths & Variables in JavaScript

Part 1 - Maths

Computers were designed to do mathematics very quickly.

JavaScript also has a Math object to perform more complex operations.

Task (Part 1)

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"?

Variables in JavaScript are very similar:

let w = 2;

let apples = 7;

let myList = w + apples;  // sets the variable 'myList' to 9

console.log(myList);      // output the value of 'myList'

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

let a, b, c;   // declare three variables

a = 3;

b = 7;

c = -9;

// positive outcome

let x = (-1*b + Math.sqrt(b**2 - 4*a*c))/(2*a);


// negative outcome

x = (-1*b - Math.sqrt(b**2 - 4*a*c))/(2*a);


Variables can be different types of data:

let myNumber = -45;
let myString = "Some text, in quotes";
let myBoolean = true;   // or false



(Tutorial on variables) (w3schools reference)

Task (Part 2) in Replit


Code is executed line-by-line, in the order you type it.

Code windows typically have numbers on each line to easily talk-about and find specific areas. 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:

SyntaxError: Unexpected token ')'