Math in Code Lesson

Mathematical expressions combine numbers with operators to create a new value. JavaScript can add, subtract, multiply, divide, and calculate remainders. These expressions are used for movement, layout, scoring, totals, and measurements.

Parentheses matter because they control which part of the expression happens first. Clear math is not only about getting the right answer; it also helps another developer understand the formula quickly.

Symbol What it does Example
+ Adds two values score + 10
- Subtracts one value from another health - damage
* Multiplies values width * height
/ Divides one value by another distance / time
% Finds the remainder after division coins % 2
() Groups part of an expression so it runs first (x + y) / 2

Code Runner Challenge

Math in Code Lesson

View IPYNB Source
%%js

// CODE_RUNNER: Math in Code Lesson

const width = 320;
const height = 180;
const area = width * height;
const centerX = width / 2;
const centerY = height / 2;

console.log("Area: " + area);
console.log("Center: " + centerX + ", " + centerY);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

The area formula uses multiplication, while the center point uses division. Both values could be used to draw or position something on a canvas.