LESSON 03 OF 10
Operators and Strings
Calculate results, compare values, and build messages.
Before this lesson: complete the preceding lessons or review their examples. No installation or account is needed.
The idea
Operators combine or compare values. The + operator adds numbers but also joins strings. Template literals use backticks and ${expression} to place a value into text. Prefer === for comparisons that should not convert types.
At a glance
| Syntax | Purpose |
|---|---|
+ - * / | Arithmetic with numeric operands |
=== and !== | Compare without type conversion |
Number() | Convert a value to a number |
Try it yourself
Predict each result before running the example.
Ready. Run the example to open its preview.
Console output
Not run yet.
Page preview
Expected result
Total: $36 52 7 false
What to watch for
Assignment (=) stores a value. Equality (===) compares values. An input element’s value is usually a string. Check empty input before converting it, because Number("") is 0. Invalid numeric text converts to NaN.
Your turn
Calculate the cost of 4 notebooks at $3 each and print a message using a template literal.
Show one solution
const total = 4 * 3;
console.log(`Notebooks cost $${total}`);Check your understanding
Why does "5" + 2 produce "52"?
One operand is a string, so + performs string concatenation in this example. Convert the string first when you want numeric addition.