Lesson 2
22 min
let , const , var and types: numbers, strings, booleans...
Definition
A variable is a named space in the computer's memory used to store a value so it can be read or modified later in the program. The data type of a value (number, text, boolean, object...) indicates the nature of the stored information and determines which operations can be performed on it. In JavaScript, a variable is declared withletor const.
A variable is a named space in memory that lets you store a value to reuse it later in your code: a number, a text, a boolean, a list, an object... Every JavaScript application, however simple, relies on variables: they are used to remember the state of a form, a game's score, the name of a logged-in user, and so on.
In modern JavaScript, a variable is declared with one of two keywords:let or const.
To picture a variable, imagine a labeled box. The label is the variable's name (age, for example) and the content of the box is its value (25). You can open the box to read what it contains and, depending on the case, replace its content with something else. Without a label, it would be impossible to find the right box among hundreds of others: this is why choosing the name matters.
Working with a variable happens in three steps: declaringit (creating the box and giving it a name), assigning it a value (putting something in it with the = sign), thenusing it (reading its content by simply writing its name).
// Declaration and assignment on a single line
let city = "Antananarivo";
// Declaration first, assignment afterwards
let temperature;
temperature = 24;
// Usage: we simply write the variable's name
console.log(city); // "Antananarivo"
console.log(temperature); // 24
// A variable can be used in a calculation
let temperatureTomorrow = temperature + 2;
console.log(temperatureTomorrow); // 26Be careful: the = sign does not have the same meaning as in mathematics. It does not mean "is equal to" but"receives the value of". The lineage = 26 is therefore read: "the variable agereceives the value 26".
let age = 25; // can be reassigned
const firstName = "Léa"; // cannot be reassigned
age = 26; // works: "let" allows reassignment
firstName = "Sam"; // error: "const" cannot change its valuelet: use it for a value that will change as the program runs (a counter, a status...).const: to be preferred by default, for a value that will not change (a configuration, an identifier...).var: the old way of declaring a variable, inherited from the early days of JavaScript. It behaves less predictably (function scope rather than block scope) and should be avoided in modern code.A good reflex is to always start with const, and switch tolet only if you know the variable will need to be reassigned later. This makes the code more predictable and easier to read.
// Best practice: const by default
const siteName = "My Blog";
// let when the value must change
let playerScore = 0;
playerScore = playerScore + 10; // the score changes as the game goes onThe scope of a variable is the area of the code in which it exists. With let and const, a variable only exists inside the block (the curly braces) where it was declared. With var, it "leaks" out of the block, which is a source of hard-to-spot errors.
if (true) {
let message = "Only visible inside this block";
var old = "Also visible outside (trap!)";
console.log(message); // works
}
console.log(old); // "Also visible outside (trap!)"
console.log(message); // error: message is not definedThis is one of the main reasons we avoid var:let and const limit the scope to what is strictly necessary, which avoids unpleasant surprises.
const does not mean "frozen forever"
const forbids reassigning the variable, but does not prevent modifying the content of an array or an object it references. We will come back to this in the lessons dedicated to arrays and objects.
_ or a $ (never with a digit).age and Age are two different variables.myFirstName, totalPrice, isLoggedIn.d is a bad name, durationInMinutes is a good one.totalPrice, not total price or total-price.let, const, if, class or return.// Valid and readable names
let totalPrice = 120;
let isLoggedIn = true;
const VAT_RATE = 0.2; // "fixed" constants are often written in UPPERCASE
// Invalid names
// let 2nd = "no"; // starts with a digit
// let total price = 120; // contains a space
// let class = "Grade 12"; // reserved word
// Valid names, but to be avoided
let x = 120; // too vague
let Totalprice; // a leading capital letter is reserved for other usesA variable declared with let can be modified as many times as needed. To avoid repeating its name, JavaScript offers shortenedassignment operators, widely used for counters and totals:
let total = 10;
total += 5; // equivalent to total = total + 5 -> 15
total -= 3; // equivalent to total = total - 3 -> 12
total *= 2; // equivalent to total = total * 2 -> 24
total /= 4; // equivalent to total = total / 4 -> 6
let counter = 0;
counter++; // adds 1 -> 1
counter++; // adds 1 -> 2
counter--; // removes 1 -> 1
console.log(total, counter); // 6 1These shortcuts only work with let: trying to apply them to a const variable causes an error.
JavaScript offers several data types to represent different kinds of information:
const number = 42; // number: integers and decimals
const price = 19.99; // number too
const text = "Hello"; // string: a sequence of characters
const isActive = true; // boolean: true or false
const nothing = null; // null: deliberate absence of a value
let notDefined; // undefined: value not yet defined
const bigNumber = 12345678901234n; // bigint: very large numbers (rare)
const uniqueId = Symbol(); // symbol: a unique value (rare)'...', double quotes "..." or backticks `...`.true or false, widely used in conditions.A type is called primitive when its value is simple andimmutable: you cannot modify it "from the inside", you can only replace it with another one. Let's take a closer look at the four types you will use most often.
Integers, decimals, positive or negative: all are of typenumber. The usual mathematical operators can be applied to them. Two special values exist: Infinity (the result of a division by zero) and NaN ("Not a Number"), which signals an impossible calculation.
console.log(10 + 5); // 15 (addition)
console.log(10 - 5); // 5 (subtraction)
console.log(10 * 5); // 50 (multiplication)
console.log(10 / 4); // 2.5 (division)
console.log(10 % 3); // 1 (remainder of the division: the modulo)
console.log(2 ** 3); // 8 (power: 2 to the power of 3)
console.log(10 / 0); // Infinity
console.log("abc" * 2); // NaN: impossible to multiply textA string is created with quotes. You can concatenate(join) strings with the + operator, or, more elegantly, usetemplate literals: a text surrounded by backticks in which you insert variables with the ${variable}syntax.
const firstName = "Léa";
const age = 28;
// Concatenation with +
console.log("My name is " + firstName + " and I am " + age + " years old.");
// Template literal with backticks (more readable)
console.log(`My name is ${firstName} and I am ${age} years old.`);
// A few useful properties and methods
console.log(firstName.length); // 3 (number of characters)
console.log(firstName.toUpperCase()); // "LÉA"
console.log(firstName.toLowerCase()); // "léa"A boolean can only take two values: true orfalse. It is most often the result of acomparison, and it will be used in the following lessons to make decisions with conditions.
const isAdult = true;
console.log(18 > 15); // true
console.log(5 === 5); // true (strict equality)
console.log(5 === "5"); // false (a number is not a string)
console.log(3 !== 4); // true (not equal to)In JavaScript, some values are considered false in a condition: false, 0, "" (empty text), null, undefined and NaN. All other values are considered true. These are called "falsy" and "truthy" values.
undefined is the value JavaScript gives to a variable that is declared but never initialized: it appears "on its own".null, on the other hand, is set deliberatelyby the programmer to say "there is nothing here for now".
let cart; // declared without a value
console.log(cart); // undefined
let loggedInUser = null; // deliberately empty
console.log(loggedInUser); // nullIn addition to primitive types, JavaScript offers more complex types to group several values together:
const fruits = ["apple", "kiwi", "banana"]; // an array
const user = {
name: "Léa",
age: 28,
}; // an objectArrays and objects will be covered in depth in two dedicated lessons later in this course.
For now, just remember that an array is an ordered list of values, retrieved by their position (starting at 0), and that an object is a set of "name: value" pairs, retrieved by their name.
console.log(fruits[0]); // "apple" (the first element is at index 0)
console.log(fruits.length); // 3
console.log(user.name); // "Léa"
console.log(user.age); // 28The typeof operator lets you find out the type of a value, which is very useful for debugging or validating data before using it.
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (a historical quirk of JS!)
console.log(typeof [1, 2, 3]); // "object" (an array is a special kind of object)
console.log(typeof { a: 1 }); // "object"The result of typeof is always a string. To tell an array apart from a "regular" object, use Array.isArray() instead.
Debugging tip
When a result looks strange, display the value and its type side by side with console.log(value, typeof value): you will immediately spot a number that was actually text.
It often happens that a value is not of the expected type. For example, everything prompt() returns is text, even if the user typed a number. You then need to convert the value explicitly.
const input = "25"; // text, even though it looks like a number
console.log(Number(input)); // 25 (conversion to number)
console.log(parseInt("42px")); // 42 (reads the integer at the start of the text)
console.log(parseFloat("3.14")); // 3.14
console.log(String(123)); // "123" (conversion to string)
console.log(Boolean(0)); // false
console.log(Boolean("text")); // trueJavaScript can also convert types automatically in some cases: this is called coercion. It sometimes gives surprising results, which is why it is important to convert values yourself:
console.log("5" + 3); // "53": the + concatenates as soon as text is present
console.log("5" - 3); // 2 : the - forces conversion to a number
console.log(Number("5") + 3); // 8: explicit conversion, clear resultJavaScript is a dynamically typed language: you never specify a variable's type when creating it, and the same variable can, in theory, change type during its lifetime (even though this is generally not good practice).
let value = "Hello"; // value is a string
value = 42; // value becomes a number
// possible in JS, but to be avoided: it makes the code harder to followConversely, languages such as Java or C++ arestatically typed: the type is declared once and for all and can no longer change. Dynamic typing offers flexibility, but demands more rigor on your part.
const: the browser displays the error Assignment to constant variable.let in the same block.totalPrice and totalprice are two distinct variables."5" + 3 gives "53".= (assignment) and === (strict comparison).Exercise 1: declare and type
In a new JavaScript file:
firstName containing your first name (string).age containing your age (number).likesJs containing a boolean indicating whether you like JavaScript.typeof and console.log().Exercise 2: let and const
Create a variable score with let and a variable gameName with const:
score to 0, then add 10 points twice.gameName and observe the error displayed in the console.Exercise 3: conversion
Use prompt() to ask the user for two numbers, then display their sum with alert(). First test without any conversion: what happens? Then fix your code with Number() to get the correct result.
const by default, and let only if the value needs to change.var, which belongs to an older and less predictable syntax.let and const, the variable only exists within its block (block scope).typeof lets you check the type of a value at any time.Number(), String() or Boolean() to avoid the surprises of coercion.