Strings and Numbers
Programming Languages · JavaScript Basics · 12 min
Do maths, join text together, and use handy string tools like .length and .toUpperCase().
Maths operators
JavaScript is a calculator too: + adds, - subtracts, * multiplies and / divides. It works on variables as well as plain numbers.
let apples = 6;
console.log(apples - 2); // 4
Print
a * b.Print
a / b.
Leftovers with %
% is the remainder operator: it divides and gives you what's left over.
console.log(10 % 3); // 1, because 3 fits 3 times and 1 is left
It's handy for things like "is this number even?" (n % 2 is 0 for even numbers).
17 cookies are shared out evenly between 5 kids. Print how many are left over, using
%with the two variables.
Joining strings
+ on two strings glues them together. This is called concatenation. Spaces don't appear by magic, so add one yourself:
console.log("ice" + "cream"); // icecream
console.log("ice" + " " + "cream"); // ice cream
Create
fullNameby joiningfirst, a space, andlast.Print
fullName.
Template literals
Joining with + gets messy fast. A template literal is a string in backticks (`). Inside it, ${ } drops in any value:
let pet = "dog";
console.log(`I have a ${pet}`); // I have a dog
Print
I ate 8 slices of pizzausing one template literal with${slices}and${item}.
String tools
Strings come with built-in tools. Put a dot after the string:
let word = "hello";
console.log(word.length); // 5 letters
console.log(word.toUpperCase()); // HELLO
console.log(word.includes("ell")); // true
.includes() answers yes or no: true or false.
Print how many letters are in
word.Print
wordin capital letters.Print whether
wordincludes"script".
Put it together: a welcome message
Combine a variable, a string tool and a template literal. You can call a tool right inside ${ }, like ${name.length}.
Create
shoutset tofirstNamein capital letters.Print
Welcome, GRACE! Your name has 5 letters.with a template literal that usesshoutandfirstName.length.
More in JavaScript Basics
Previous: Variables · Next: Conditionals