JavaScript — The basics

Guide 01 / 4

JavaScript glossary

Give meaning to JavaScript terms by tying them to the recipe mini-blog.

Expected outcome :

Explain the concepts in your own words and recognise them in an example.

Reading
0%

01 · Getting your bearings before you start

Step 3/6 of the “À table !” running project, a recipe mini-blog. Go at your own pace: read, reproduce, modify, then check.

The path and the outcome of this step

Let users search for a recipe by its title and duration, display the number of results and reset the filters without reloading the page. The same dataset runs through all six courses: Soupe de carottes (20 min), Salade de tomates (10 min), Tarte aux pommes (45 min).

01. HTML : structurer trois recettes dans une page sémantique.
02. CSS : rendre le blog lisible sur mobile et sur ordinateur.
03. JavaScript : filtrer les recettes sans recharger la page.
04. PHP : produire les pages depuis des tableaux et traiter un formulaire.
05. MySQL : conserver les recettes dans une base relationnelle.
06. PDO : lire et ajouter des recettes depuis PHP avec des requêtes préparées.
Remember :

Each course has four guides: glossary, essentials, workshop and resources. The complete files are at the end of the workshop.

Prerequisites and environment

Have finished HTML and CSS. Keep the mini-blog's index.html and style.css, with filtres, recherche, duree-max, compteur and aucun as identifiers. Check the data-titre and data-duree attributes of the three articles. Use a local HTTP server: for example python3 -m http.server 8080 if Python 3 is available.

mini-blog/
  index.html       # HTML, CSS et JavaScript
  style.css        # ajouté à l’étape CSS
  app.js           # ajouté à l’étape JavaScript
  public/          # pages PHP accessibles par HTTP
  includes/        # fonctions, connexion et données PHP
  database/        # scripts SQL
Remember :

Create this working folder separately from the Technipédia course files. The example paths are relative to mini-blog/. Do not replace the HTML page of this platform.

The method: understand, reproduce, transform

Read a sheet, then type its example. Explain what changes on screen. Change one thing at a time and compare with the expected result. Keep a copy of the previous step before moving on.

1. Je lis et je reformule.
2. Je reproduis dans mon mini-blog.
3. Je change une valeur ou une règle.
4. Je vérifie et j’explique le résultat.
Remember :

Short snippets illustrate a concept; only the files announced as complete are to be copied as they are. Fragments are not to be concatenated into a single file.

02 · Naming and transforming data

JavaScript is a programming language. Here, it runs in the browser.

Statement and console

A statement asks for an action. The developer tools console lets you observe values and errors.

console.log("Le mini-blog est prêt");
Remember :

Only type code you understand into your own project's console.

const and let

const declares a variable that is not reassigned; let is used when its value must be reassigned, like a counter.

const titre = "Soupe de carottes";
let visibles = 0;
visibles += 1;
Remember :

const does not make an object's content immutable; it forbids replacing the stored reference.

Types of values

A string represents text; a number is used for calculation; a boolean is true or false; null here represents the absence of a result.

const titre = "Soupe";
const duree = 20;
const rapide = true;
const elementAbsent = null;

Array and object

An array holds several values; an object gathers named properties. Objects suit structured recipes.

const recette = { titre: "Soupe de carottes", duree: 20 };
const titres = ["Soupe", "Salade", "Tarte"];
console.log(recette.titre, titres[0]);
Remember :

Array indexes start at 0.

Function, parameter and return

A function groups reusable processing. The parameter receives a piece of data; return sends back the result.

function estRapide(duree) {
  return duree <= 20;
}
console.log(estRapide(10)); // true

Condition and logical operator

if runs a block depending on a condition. && requires two true conditions; || requires at least one; ! inverts a boolean.

const afficher = true && (20 <= 20);
if (afficher) { console.log("Visible"); }
Remember :

=== compares without automatic type conversion. "20" === 20 is false.

03 · Connecting the program to the page

The DOM and events make it possible to react to user actions.

DOM and selection

The DOM represents the page's elements. querySelector returns the first matching element, or null; querySelectorAll returns a list of matches.

const recherche = document.querySelector("#recherche");
const cartes = document.querySelectorAll(".recette");

Event and listener

An event signals an action: typing, a change of selection or a form submission. A listener runs a function in response.

recherche.addEventListener("input", filtrerRecettes);
Remember :

Pass the function without parentheses so that it runs on the event, not immediately.

dataset and conversion

dataset gives access to an element's data-* attributes. Their values are strings; Number converts a numeric value for comparisons.

const carte = document.querySelector(".recette");
console.log(carte.dataset.titre);
console.log(Number(carte.dataset.duree));
Remember :

A data-duree-max attribute would be read as dataset.dureeMax. Number("20") gives 20.

State and progressive enhancement

State is the set of values that drive the display: input, duration, visibility. The content must remain usable if JavaScript is not run.

formulaire.hidden = false; // après initialisation réussie
Remember :

Without JavaScript, the recipes stay visible and the inactive form stays hidden.

textContent and inserting text

textContent displays a string as text. It is the right choice for a counter or user input that must not become HTML.

compteur.textContent = "2 recettes affichées.";
Remember :

Avoid putting user input in innerHTML. The complete filtering does not need it.