Kodokon kodokon.com

Variables (let, const) and primitive types

Discover how to store information with let and const, and identify the basic value types in JavaScript.

6 min · 3 questions

Open this lesson in Kodokon

Welcome to your first JavaScript course! JavaScript is the programming language that makes web pages interactive: it is what reacts when you click a button or fill in a form. A program is a series of instructions that the computer executes in order. To do its job, a program needs to remember information: that is what variables are for. Think of a variable as a box with a label: the label is its name, the contents are its value.

JAVASCRIPT
let age = 25;
console.log(age); // Prints: 25
age = 26;
console.log(age); // Prints: 26
Declaring a variable with let, then changing its value

Let's break this code down. The let keyword creates a variable named age. The = sign, called an assignment, puts the value 25 into the box. The console.log(...) instruction prints a value to the screen: it is your main tool for observing what your program is doing. Finally, the line age = 26; replaces the contents of the box: with let, a variable can change value. When a value should never change, you use the const keyword instead (short for "constant").

JAVASCRIPT
const birthYear = 2000;
console.log(birthYear); // Prints: 2000
// birthYear = 2001; -> would cause an error
Declaring a constant with const

Every value has a type, that is, a category that determines what you can do with it. The main primitive types (the simplest types) are: string (a string of characters, in other words text between quotes), number (a number, whole or decimal), boolean (a boolean: true or false), undefined (the type of a variable declared without a value) and null (the deliberate absence of a value). The typeof operator reveals the type of a value.

JAVASCRIPT
const city = "Paris";
const temperature = 21.5;
const isSunny = true;
let score;
console.log(typeof city);        // "string"
console.log(typeof temperature); // "number"
console.log(typeof isSunny);     // "boolean"
console.log(typeof score);       // "undefined"
The most common primitive types

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which keyword declares a variable whose value can never be reassigned?
    • let
    • const
    • typeof
    • value
  2. What is the type of the value "Hello"?
    • number
    • boolean
    • string
    • undefined
  3. What happens if you run age = 26; when age was declared with const?
    • The value is replaced with 26
    • JavaScript throws an error
    • The variable becomes undefined