Strings and numbers
You'll learn to build text with template literals and to tell joining text apart from adding numbers.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want to show a line like Total for Rafi: 360 taka. Part of it is fixed text, and part of it comes
from variables. You also need the maths to be right.
Text in quotes is a string: "Rafi". A number has no quotes: 120. They look similar on screen, but
JavaScript treats them very differently.
The easiest way to build text is with backticks, called a template literal. Anything inside ${ }
is worked out and placed into the text:
const name = "Rafi";const price = 120;console.log(`Total for ${name}: ${price * 3} taka`);// Total for Rafi: 360 taka
The + sign does two jobs. With two numbers it adds: 5 + 1 is 6. If either side is a string, it
joins text: "5" + 1 is "51". People often hit this with form inputs. A text box always gives you
a string, even when the user types a number. Turn it into a number first with Number("5").
Money needs one more step. 99.5 * 3 is 298.5, but you want 298.50. total.toFixed(2) gives a
string with exactly two digits after the point. Use it only when you show the value, not while you still
calculate.
Strings have handy tools too. name.length counts the characters, and name.toUpperCase() gives a new
string in capitals.
When you read code with +, check both sides. If either side could be a string, expect joined text.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1const input = "20";2console.log(input + 5);3console.log(Number(input) + 5);
bill and tip come from text boxes, so they are strings. total should be the number 120. Fix the code so both checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3What is
"10" + 5? - 2 / 3With
const runs = 45;, what text does the template literalScore: ${runs + 5}make? - 3 / 3What does
(12.5).toFixed(2)give?
Explain it back
How confident are you with Strings and numbers?
Done
+ will add numbers or join text, and fix it with Number().