JavaScriptLesson 3 of 16
Numbers and operators
JavaScript counts like a calculator, only faster and with a couple of surprises. Let’s look at operators, remainders and rounding.
Key points
- + - * / are the usual maths, ** is a power: 2 ** 10 is 1024
- % gives the remainder of a division: 7 % 3 is 1
- Math.floor rounds down, Math.round rounds normally, Math.max picks the largest
- 0.1 + 0.2 gives 0.30000000000000004, so money is rounded with toFixed(2)
- "5" + 2 glues text into "52", while Number("42") turns text into a number
Example
console.log(7 + 3, 7 - 3, 7 * 3, 7 / 2);console.log(7 % 3, 2 ** 10);console.log(0.1 + 0.2);console.log((0.1 + 0.2).toFixed(2));console.log(Math.round(4.6), Math.floor(4.6), Math.max(3, 9, 1));console.log("5" + 2, "5" * 2, Number("42") + 1);The last line is a classic trap: with a plus, text wins and gets glued, while multiplying turns "5" into a number. toFixed returns a string with as many decimals as you ask for.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Seven friends share three pizzas of 12 slices, and a pizza costs 11.5. Print three lines: Slices each: 5 (whole slices per friend), Left over: 1 (what remains) and Each pays: 4.93 (each share, rounded to cents).
Output
What your program prints appears here.