JavaScript · Beginner level

Beginner level · Module 1: JavaScript Setup and Basics · Lesson 3 of 3

Operators, Strings and Template Literals

Calculate with arithmetic operators, build readable text with template literals and use common string methods.

In this lesson you will

  • Use arithmetic and comparison operators
  • Build text with template literals and string methods

Key concepts

arithmetic operatorstemplate literals `${}`toFixed and toLocaleStringstring methods

The lesson

JavaScript has the usual operators: + - * /, % for the remainder and ** for powers. Decimal arithmetic can produce tiny rounding errors such as 0.1 + 0.2 = 0.30000000000000004; for money, work in whole units such as SSP or cents and format the result for display.

Template literals use backticks and ${} to insert values: `Total: ${total} SSP`. They are clearer than joining strings with + and can span several lines.

Strings have useful methods: toUpperCase(), trim(), includes(), slice(), replace() and padStart(). Numbers can be formatted with toFixed(2) or toLocaleString("en-US") for thousands separators.

Step by step

  1. Calculate the cost of 3 items at 3,500 SSP.
  2. Print it in a template literal with toLocaleString.
  3. Trim and capitalise a messy name.
  4. Calculate a 15% discount and format it with toFixed(2).

Practice activity

Complete the data-bundle comparison activity, printing one formatted sentence per offer with the cost per GB.

Expected result: Each offer prints a clear sentence with the correct cost per GB to two decimal places.

Check your understanding

  1. How do you insert a variable into a template literal?

    Show answer

    With ${variable} inside a backtick string.

  2. Why is 0.1 + 0.2 not exactly 0.3?

    Show answer

    Decimal fractions are stored in binary floating point, which cannot represent them exactly.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.