Variables, Types, and Operators

First lesson of the JavaScript Fundamentals course, free to read: about 15 minutes, 3 exercises and 3 quiz questions. This is the catalogue's base lesson; in the student space, it is rewritten for your profile.

Objectives

  • Declare variables with const and let
  • Recognize primitive types and use typeof
  • Build strings with template literals and compare with ===

Variables (const, let)JavaScript primitive typesOperators and comparisons

JavaScript is the programming language of the Web: it runs in every browser to make pages interactive, and on the server with Node.js. In this course, our exercises run with Node, without a web page: we focus on the language itself.

Declaring variables

const prixUnitaire = 19.9;   // const: cannot be reassigned
let quantite = 2;            // let: can change
quantite = 3;                // OK
// prixUnitaire = 25;        // TypeError: assignment to a constant

console.log(prixUnitaire * quantite); // prints 59.7 (approximately, see below)

Simple rule: use const by default, and let only if you must reassign the variable. The old var keyword has tricky behaviors (function scope, declaration “hoisting”): it is no longer used in modern code.

Names follow the camelCase convention (prixTotal, estConnecte) and should be meaningful.

Primitive types

const nom = "Léa";             // string
const age = 31;                // number (integers and decimals)
const estAbonne = true;        // boolean
let commentaire;               // undefined: declared without a value
const coupon = null;           // null: deliberate absence of a value
const grandNombre = 9007199254740993n; // bigint: arbitrarily large integers

console.log(typeof nom);       // "string"
console.log(typeof age);       // "number"
console.log(typeof null);      // "object": a historical quirk to know about

There is also the symbol type, which is rarer. Everything else (arrays, objects, functions) is of the object type.

Operators and strings

const total = 10 + 5 * 2;      // 20: multiplication takes precedence
const reste = 17 % 5;          // 2: remainder of the division (modulo)
const carre = 3 ** 2;          // 9: exponentiation
let compteur = 0;
compteur += 1;                 // compteur = compteur + 1
compteur++;                    // increments by 1

// Template literals (backticks): insert expressions with ${...}
const message = `Hello ${nom}, you are ${age} years old.`;
const ligne = `Total : ${(19.9 * 3).toFixed(2)} €`;  // "Total : 59.70 €"

Strings have many methods: nom.length, nom.toUpperCase(), texte.trim(), texte.includes("@"), texte.split(","), texte.padStart(2, "0").

Comparing: always with ===

5 === 5        // true
5 === "5"      // false: different types
5 == "5"       // true: == converts types before comparing (trap)
0 == false     // true (!)
null == undefined // true

=== and !== compare without conversion: use them systematically. Other operators: <, >, <=, >=, and the logical operators && (and), || (or), ! (not).

Converting explicitly

Data coming from a form or a URL are strings. You need to convert them:

const saisie = "42";
const n = Number(saisie);           // 42
"3" + 4                             // "34": + concatenates if a string is present
Number("3") + 4                     // 7
Number("douze")                     // NaN (Not a Number)
Number.isNaN(Number("douze"))       // true
Number.parseFloat("12.5 kg")        // 12.5: reads the start of the string
String(42)                          // "42"

The decimal trap

0.1 + 0.2              // 0.30000000000000004

Numbers are stored in binary floating point: some decimals cannot be represented exactly. For money, calculate in whole cents (1990 rather than 19.90) and format only for display.

Exercises

Solutions and tests stay on the server. In the student space, your code is run and checked, and the tutor gives hints before the solution.

  1. CodeDifficulty 1JavaScript in the browser2 hints

    Welcome message

    Declare a constant prenom equal to "Inès" and a constant nbArticles equal to 3. Then create the constant message with a template literal to get exactly: Bonjour Inès, votre panier contient 3 articles.

    // déclarez prenom, nbArticles puis message
  2. CodeDifficulty 2JavaScript in the browser3 hints

    Convert and calculate

    The values saisiePrix and saisieQte come from a form (they are strings). Calculate totalCentimes, the total in whole cents (price x quantity x 100, rounded with Math.round), then affichage in the format "Total : 59.70 €" (two decimals with toFixed(2)).

    const saisiePrix = "19.90";
    const saisieQte = "3";
    // vos calculs
  3. CodeDifficulty 1JavaScript in the browser1 hint

    Strict comparison

    Write the function memeValeurEtType(a, b) that returns true if a and b are strictly equal (same value and same type), false otherwise.

    function memeValeurEtType(a, b) {
      // votre code
    }

End-of-lesson quiz

  1. What is “3” + 4 in JavaScript?

    • 7
    • "34"
    • NaN
  2. Which keyword should you use by default to declare a variable?

    • var
    • let
    • const
  3. What does typeof null return?

    • "null"
    • "object"
    • "undefined"

The rest of the course

  1. Conditions and Loops20 min
  2. Functions20 min
  3. Arrays and Their Methods20 min
  4. Objects and JSON20 min
  5. Handling Errors and Organizing Code into Modules15 min

JavaScript Fundamentals · Beginner · 3 h 50 min