JavaScript · Beginner level

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

Variables and Types

Store values with const and let, recognise JavaScript's main types and avoid common type surprises.

In this lesson you will

  • Choose between const and let
  • Identify types with typeof and convert between strings and numbers

Key concepts

const vs letnumber, string, booleannull and undefinedNumber() and typeof

The lesson

Use const for values that will not be reassigned and let for values that will; avoid the old var. Starting with const makes code easier to follow, because a reader knows the value does not change.

JavaScript's main types are number (both whole and decimal), string, boolean, undefined (no value assigned yet) and null (deliberately empty), plus objects. typeof shows a value's type.

Input from forms and prompts is always text. "5" + 3 gives "53" because + joins strings, while "5" * 3 gives 15. Convert explicitly with Number(text) and check the result with Number.isFinite before calculating.

Step by step

  1. Declare a price with const and a quantity with let.
  2. Print typeof for a number, a string, true, null and undefined.
  3. Try "5" + 3 and "5" * 3 in the console.
  4. Convert a text value with Number() and check it with Number.isFinite.

Practice activity

Write a script that converts three text prices to numbers, skips one that is not a valid number and prints the total.

Expected result: The valid prices are totalled correctly and the invalid one is reported, not added.

Check your understanding

  1. What is "5" + 3 in JavaScript?

    Show answer

    "53" — the + operator joins strings.

  2. When should you use const?

    Show answer

    For any variable that is not reassigned.

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.