The goal of the code was to complete the steps in the following order:
- add 6 to 4 = 10
- divide the result by 2 = 5
- subtract 1 from the result = 4
- multiply the result by 18 = 72
In Blocks, each step of an equation needed it’s own block. This can make formulas difficult to properly express, as it can be hard to identify (or change) the order in which they are evaluated.
In JavaScript, the same formulas can be easier to express, as the syntax (structure) is much closer to what is used when evaluating math by hand or with a scientific calculator.
Operation | Block | JavaScript |
---|---|---|
Addition | [let x = (6 + 2)] |
let x = 6 + 2; |
Subtraction | [let x = (6 - 2)] |
let x = 6 - 2; |
Multiplication | [let x = (6 * 2)] |
let x = 6 * 2; |
Division | [let x = (6 / 2)] |
let x = 6 / 2; |
||game:game.splash||
to display the value)let num: number = 1 + 2 - 3;
let num: number = 1 + 2 - 3;
let num: number = 5 + 3 * 2;
let num: number = 5 + 3 * 2;
let num: number = 24 / 3 * 4;
let num: number = 24 / 3 * 4;
+
to a ×
, and switch back to JavaScript.
What has changed?let num: number = 15 + 8 / 3
JavaScipt uses a PEMDAS structure to determine the order in which operations are evaluated. This standards for Parentheses, Exponents, Multiplication or Division, Addition or Subtraction.
Order | Operation |
---|---|
1st | Parenthesis |
2nd | Exponents |
3rd | Multiplication |
Division | |
4th | Addition |
Subtraction |
Operations of the first order will occur before operations of the second order, operations of the second order will occur before operations of the third order, and operations of the third order will occur before operations of the 4th order.
Operations that are of the same order (for example, multiplication and division)
will be completed left-to-right.
This means that 24 / 3 * 4
evaluates to 32
,
because 24
is divided by 3
, then the result is multiplied by 4
.
Parentheses have the highest order, which means that they are always evaluated first.
This can be used to control the order in which an expression is evaluated.
For example, 24 / (3 * 4)
will evaluate to 2
,
because the parentheses require that 3 * 4
is evaluated first,
before the division occurs.
||variables:num||
is changed using the order of operationslet num: number = 10 - 6 / 2;
console.log("" + num);
This will print out the number 7, because the division occurs before the subtraction.
If instead the goal is to subtract before dividing, parentheses can be used to change the order
let num: number = (10 - 6) / 2;
console.log("" + num);
This will print out the number 2 instead.
let num: number = 24 / 3 * 4;
console.log("" + num);
This will print out the number 32, because the division occurs before the multiplication.
If instead the goal is to multiply first, the equation can be changed using parentheses
let num: number = 24 / (3 * 4);
console.log("" + num);
This will print out the number 2 instead.
||variables:num||
storeslet num: number = 18 * 6 + 4 / 2 - 1;
game.splash("" + num);