Without notes, state yesterday’s main idea and one unresolved question.
Operators and expressions
JavaScript Foundations I
Objective
Translate simple engineering formulas into readable code.
Variables are measured signals, functions are reusable circuit blocks, and control flow determines which path becomes active.
- arithmetic operators
- comparison operators
- operator precedence
Why this matters
Yesterday you stored values. Today you combine them, which is where a program stops being a list of facts and starts producing answers. By the end of the hour you can turn Ohm's law and the power formula into code that runs, and — just as important — you can tell whether the number it printed is right.
Formulas are where beginners get burned, because JavaScript will happily compute a wrong answer without complaining. Nothing here is hard; all of it is precise.
Expressions and arithmetic operators
An expression is any piece of code that produces a value. 9 is an expression. So is
9 / 470. An operator is a symbol that combines values — the / there.
JavaScript's arithmetic operators:
| Operator | Does | Example | Result |
|---|---|---|---|
+ |
add | 220 + 330 |
550 |
- |
subtract | 9 - 5 |
4 |
* |
multiply | 9 * 0.02 |
0.18 |
/ |
divide | 9 / 470 |
0.019148936170212766 |
% |
remainder | 7 % 3 |
1 |
** |
power | 2 ** 10 |
1024 |
% (called modulo) gives what is left after dividing: 7 % 3 is 1 because 3 goes into 7
twice with 1 spare. It is how you test divisibility later.
An expression can be stored in a variable. That is the single most useful habit today:
const voltageVolts = 9;
const resistanceOhms = 470;
const currentAmps = voltageVolts / resistanceOhms;
console.log(currentAmps);
0.019148936170212766
currentAmps is a named intermediate value: a step of the calculation given a name. Compare
9 / 470 * 9 with voltageVolts * currentAmps. Both compute power; only one can be checked by
reading it.
Naming intermediates is labelling test points
On a board you do not measure the output and hope. You label V_in, I_load, V_drop, and probe
each one, so a wrong final reading tells you which stage failed. Named intermediates are
those labels: when the power figure is wrong, you print currentAmps and find out whether the
fault is before or after that point.
When + is not addition
+ has a second job: joining strings. If either side is a string, + concatenates instead of
adding.
console.log("10" + 5);
console.log("10" - 5);
105
5
The first is "10" glued to "5". The second has no string meaning, so JavaScript quietly
converts "10" to a number and subtracts. This silent conversion is called coercion, and it
causes a great many wrong numbers.
Values from outside your program arrive as strings
Anything typed into a web form or passed on the command line is a string, even when it looks
like a number. Convert deliberately with Number("10"), which gives the number 10. Check
your inputs with typeof (Day 15) before trusting them in arithmetic.
Decimals are approximate
console.log(0.1 + 0.2);
0.30000000000000004
This is not a JavaScript bug. Computers store decimals in binary with a fixed number of bits, and some decimal fractions have no exact binary form — exactly as 1/3 has no exact decimal form. The tiny error is real and it is in every language.
The practical rule: do arithmetic at full precision, and round only when displaying.
.toFixed(n) gives a string rounded to n decimal places.
const powerWatts = 9 * 0.019148936170212766;
console.log(powerWatts);
console.log(powerWatts.toFixed(4));
0.1723404255319149
0.1723
Note .toFixed() returns a string, not a number. Use it for output, never as an input to
more maths.
Comparison operators
Comparisons produce a boolean — true or false.
| Operator | Asks |
|---|---|
=== |
are these the same value and the same type? |
!== |
are these different in value or type? |
> < |
greater than, less than |
>= <= |
greater or equal, less or equal |
=== compares value and type with no coercion. That is the whole point of it.
console.log(5 === 5);
console.log(5 === "5");
console.log(5 == "5");
true
false
true
The two-character == converts types before comparing, so the number 5 and the string "5"
count as equal. That is almost never what you want, and it hides exactly the bug the previous
section warned about. Use === and !== always.
Two kinds of "same"
== is a shop assistant who accepts a photocopy of your ID because it looks right. ===
checks that it is the real document and the right type of document. One is convenient; the
other is correct.
Thirty seconds
Run console.log(5 === "5", 5 == "5", "" == 0); in a scratch file. The third is true too.
Every one of those surprises is a bug waiting in code that uses ==.
Operator precedence
Precedence is the order operators are applied when you do not say. *, /, and % bind
tighter than + and - — the same rule as school arithmetic.
console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
14
20
Comparisons happen after arithmetic, so 2 + 3 > 4 means (2 + 3) > 4, which is true.
The professional habit is not memorising the precedence table. It is adding parentheses whenever a line is not instantly obvious: they cost nothing and remove all doubt for the next reader, who is usually you.
Walkthrough
Create calculations.js. A 9 V supply across a 470 Ω resistor.
const voltageVolts = 9;
const resistanceOhms = 470;
const currentAmps = voltageVolts / resistanceOhms;
const currentMilliamps = currentAmps * 1000;
const powerWatts = voltageVolts * currentAmps;
console.log(`Current: ${currentMilliamps.toFixed(2)} mA`);
console.log(`Power: ${powerWatts.toFixed(4)} W`);
Run node calculations.js:
Current: 19.15 mA
Power: 0.1723 W
Check it by hand: 9 ÷ 470 ≈ 0.01915 A ≈ 19.15 mA, and 9 × 0.01915 ≈ 0.172 W. The code agrees, so the formula was transcribed correctly. Doing this once per formula is the difference between a calculator and a guess.
Add resistors in series — total resistance is the plain sum:
const r1 = 220;
const r2 = 330;
const r3 = 470;
const seriesOhms = r1 + r2 + r3;
console.log("Series total:", seriesOhms, "ohms");
console.log("Above 1k:", seriesOhms > 1000);
Series total: 1020 ohms
Above 1k: true
Checkpoint
You should be able to say why powerWatts uses currentAmps and not currentMilliamps, and
what seriesOhms > 1000 evaluates to before you run it.
Your turn
Deliverable: a calculations.js file with verified example outputs.
- In
js-basics/, createcalculations.jswithconstinputs for supply voltage and three resistor values. Put the unit in every name (voltageVolts,r1Ohms). - Compute current from Ohm's law (
I = V / R) using the first resistor, storing it in a named intermediate. - Compute power two ways —
V * IandI ** 2 * R— and log both. They should agree to several decimal places. If they do not, one formula is mistyped. - Compute the series total of all three resistors.
- Log each result with a template literal, using
.toFixed(2)for display only. - Add three comparisons and log them: is current above 10 mA, is the series total
=== 1020, is power!== 0. - Verify every number with a calculator or by hand, and write the hand-checked value as a comment beside each line.
Pair mode — after step 7, not before
"Check my formula implementation against the equations I provide. Point out unit mistakes separately from code mistakes." Give it your equations and your file. Then inspect every change it suggests, run the file again, and be able to explain the behaviour before you keep any of it — an unread suggestion is not a verified one.
Common pitfalls
- Mixing units silently. Milliamps into a watts formula gives an answer 1000× too big. The code is fine; the physics is not. Units belong in variable names.
- Using
==. It coerces, so5 == "5"istrue. Use===everywhere. - Feeding
.toFixed()output back into maths. It is a string, so+will concatenate. Round last. - Trusting a decimal comparison.
0.1 + 0.2 === 0.3isfalse. Compare rounded values, or check the difference is small.
Verify it yourself
Open today's reference, MDN's Dynamic scripting with JavaScript, and find its section on basic maths and operators.
- MDN describes an operator this lesson did not: the increment
++. What does it do to a variable, and why can it not be used on aconst? - Find MDN's own advice on
==versus===. Does it agree with this lesson's rule?
Write both answers as comments at the bottom of calculations.js.
The hour
- 0–5 min Recall
- 5–20 min Learn
Read only the listed concept notes and official reference sections needed today.
- 20–48 min Build
Implement voltage, current, power, and resistor-series calculations with named intermediate values.
- 48–55 min Explain and verify
Run the result, inspect evidence, and explain the data/control flow in your own words.
- 55–60 min Quiz and commit
Complete the quiz, record one lesson, and commit the verified change when applicable.
What to hand in
A calculations.js file with verified example outputs.
Working with AI today
Define one small task, review the plan, inspect the diff, run checks, and explain every changed section.
Check my formula implementation against the equations I provide. Point out unit mistakes separately from code mistakes.
References
End-of-day quiz
Explain-back gate
Pass the quiz above to unlock completion.
Quiz + explain-back checks required.