Lesson 3
Numbers in JavaScript
+ addition operator, e.g. 2 + 2 = 4- subtraction operator, e.g. 10 - 6 = 4* multiplication operator, e.g. 5 * 6 = 30/ division operator, e.g. 8 / 4 = 2% modulo operator, returns the remainder after
dividing one number by another, e.g. 10 % 7 = 3Math.round() rounds a number to the nearest whole
number, e.g. Math.round(7.8567) = 8Math.floor() rounds a number DOWN to the nearest
whole number, e.g. Math.floor(17 / 5) = 3Math.ceil() rounds a number UP to the nearest whole
number, e.g. Math.ceil(7.1) = 8Math.random() returns a random decimal number
between 0 (included) and 1 (excluded), e.g. Math.random() = 0.732...Math.abs() returns the absolute value of a
number, e.g. Math.abs(-5) = 5Math.min() used to find the smallest of the given
numbers, e.g. Math.min(4, 9, 2) = 2Math.max() used to find the largest of the given
numbers, e.g. Math.max(4, 9, 2) = 9Number() used to convert a given value (like a
string) into a number, e.g. Number("5") = 5parseInt() converts a string into a whole number,
e.g. parseInt("5") = 5Store a Number
Task: Store your own age in a variable and print it.
console.log(age);
Basic Math
Task: Pick two numbers of your own and try all four operations.
let b = 3;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
The Remainder Operator (%)
Task: Try % with a few number pairs and guess the pattern before running it.
Numbers + Strings Together
Task: Predict the output of each line before running it, then compare.
Why they are different (string vs number)?
console.log(5 + 3);
Age in 10 Years
Task: Calculate your age in 10 years and print a sentence using a template literal.
let futureAge = age + 10;
console.log(`In 10 years I will be ${futureAge}.`);
Rounding Numbers
Task: Try Math.round() on a few decimal numbers and see how it rounds.
console.log(Math.round(price));
Random Numbers
Task: Run it several times and see the dice value change.
Why do we add +1 at the end?
console.log(dice);
Pizza Slice Splitter
Task: Change the numbers of slices/friends and recalculate.
What does Math.floor do here, and why do we need it?
let friends = 5;
let slicesEach = Math.floor(slices / friends);
let leftover = slices % friends;
console.log(`Each friend gets ${slicesEach} slices.`);
console.log(`There are ${leftover} slices left over.`);
Temperature Converter
Task: Convert 3 different Celsius temperatures (like todays weather, freezing point 0°C, and body temp 37°C) to Fahrenheit.
let fahrenheit = (celsius * 9 / 5) + 32;
console.log(`${celsius}°C is ${fahrenheit}°F`);
Allowance Growth Challenge
Task: Manually calculate savings after 8 weeks by repeating the line.
savings = savings + 5; // week 2
savings = savings + 5; // week 3
savings = savings + 5; // week 4
console.log(`After 4 weeks I will have $${savings}`);