0%
Modern JavaScript: ES6+ Features

Modern JavaScript: ES6+ Features

Discover the modern JavaScript features that have revolutionized web development.

I

InSkillCoach

· min

Modern JavaScript: ES6+ Features

Since 2015, JavaScript has undergone a major evolution with the introduction of ECMAScript 2015 (ES6) and the versions that followed. These updates have brought many features that make code cleaner, more expressive, and more powerful.

The Main ES6+ Features

1. Let and Const

Before ES6, variables were declared with var, which had scoping issues. ES6 introduced let and const:

// let: reassignable variable with block scope
let compteur = 0;
compteur = 1; // OK

// const: non-reassignable constant
const PI = 3.14159;
// PI = 3.14; // Error!

// Block scope
if (true) {
  let x = 10;
  const y = 20;
  var z = 30;
}
// console.log(x); // Error: x is not defined
// console.log(y); // Error: y is not defined
console.log(z); // 30 (var has no block scope)

2. Arrow Functions

Arrow functions offer a more concise syntax and preserve the this context:

// Regular function
function addition(a, b) {
  return a + b;
}

// Equivalent arrow function
const additionFleche = (a, b) => a + b;

// With a single parameter, parentheses are optional
const carre = x => x * x;

// With a more complex function body
const calculer = (a, b) => {
  const resultat = a * b;
  return resultat + 5;
};

// Preserving the this context
const personne = {
  nom: "Alice",
  amis: ["Bob", "Charlie"],
  
  // With a regular function
  afficherAmisClassique: function() {
    this.amis.forEach(function(ami) {
      console.log(this.nom + " connaît " + ami); // Error: this.nom is undefined
    });
  },
  
  // With an arrow function
  afficherAmisFleche: function() {
    this.amis.forEach(ami => {
      console.log(this.nom + " connaît " + ami); // Works correctly
    });
  }
};

3. Template Literals

Template literals let you embed expressions inside strings:

const nom = "Alice";
const age = 30;

// Before ES6
const message1 = "Bonjour, je m'appelle " + nom + " et j'ai " + age + " ans.";

// With template literals
const message2 = `Bonjour, je m'appelle ${nom} et j'ai ${age} ans.`;

// Multi-line strings
const html = `
<div>
  <h1>Profil</h1>
  <p>Nom: ${nom}</p>
  <p>Âge: ${age}</p>
</div>
`;

// Tagged templates
function highlight(strings, ...values) {
  return strings.reduce((result, str, i) => {
    return result + str + (values[i] ? `<strong>${values[i]}</strong>` : '');
  }, '');
}

const messageHighlight = highlight`Bonjour, je m'appelle ${nom} et j'ai ${age} ans.`;
// "Bonjour, je m'appelle <strong>Alice</strong> et j'ai <strong>30</strong> ans."

4. Destructuring

Destructuring lets you extract values from arrays and objects:

// Object destructuring
const utilisateur = {
  nom: "Dupont",
  prenom: "Jean",
  age: 30,
  adresse: {
    ville: "Paris",
    codePostal: "75001"
  }
};

const { nom, prenom, age } = utilisateur;
console.log(nom); // "Dupont"

// With aliases
const { nom: nomFamille, prenom: prenomUtilisateur } = utilisateur;
console.log(nomFamille); // "Dupont"

// Default values
const { pays = "France" } = utilisateur;
console.log(pays); // "France"

// Nested destructuring
const { adresse: { ville } } = utilisateur;
console.log(ville); // "Paris"

// Array destructuring
const couleurs = ["rouge", "vert", "bleu"];
const [premiere, deuxieme, troisieme] = couleurs;
console.log(premiere); // "rouge"

// Skipping elements
const [, , derniere] = couleurs;
console.log(derniere); // "bleu"

// Rest pattern
const [premier, ...reste] = couleurs;
console.log(reste); // ["vert", "bleu"]

// Swapping variables
let a = 5;
let b = 10;
[a, b] = [b, a];
console.log(a, b); // 10 5

5. Spread Operator

The spread operator (...) lets you expand arrays and objects:

// With arrays
const nombres1 = [1, 2, 3];
const nombres2 = [4, 5, 6];

// Concatenation
const tousLesNombres = [...nombres1, ...nombres2];
console.log(tousLesNombres); // [1, 2, 3, 4, 5, 6]

// Copying an array
const copieNombres = [...nombres1];

// With objects (ES2018+)
const personne = { nom: "Dupont", age: 30 };
const employe = { ...personne, poste: "Développeur", salaire: 45000 };
console.log(employe); // { nom: "Dupont", age: 30, poste: "Développeur", salaire: 45000 }

// Overriding properties
const personneModifiee = { ...personne, age: 31 };
console.log(personneModifiee); // { nom: "Dupont", age: 31 }

// With functions
function somme(a, b, c) {
  return a + b + c;
}

const nombres = [1, 2, 3];
console.log(somme(...nombres)); // 6

6. Default Parameters

Default parameters let you specify default values for function arguments:

// Before ES6
function creerProfil(nom, age, ville) {
  age = age || 30;
  ville = ville || "Paris";
  return { nom, age, ville };
}

// With ES6
function creerProfilES6(nom, age = 30, ville = "Paris") {
  return { nom, age, ville };
}

console.log(creerProfilES6("Alice")); // { nom: "Alice", age: 30, ville: "Paris" }
console.log(creerProfilES6("Bob", 25)); // { nom: "Bob", age: 25, ville: "Paris" }
console.log(creerProfilES6("Charlie", undefined, "Lyon")); // { nom: "Charlie", age: 30, ville: "Lyon" }

7. Rest Parameters

Rest parameters let you represent an indefinite number of arguments as an array:

// Before ES6
function somme() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

// With ES6
function sommeES6(...nombres) {
  return nombres.reduce((total, nombre) => total + nombre, 0);
}

console.log(sommeES6(1, 2, 3, 4, 5)); // 15

// Combining with regular parameters
function afficherInfos(nom, prenom, ...details) {
  console.log(`Nom: ${nom} ${prenom}`);
  console.log(`Détails: ${details.join(", ")}`);
}

afficherInfos("Dupont", "Jean", "30 ans", "Paris", "Développeur");
// "Nom: Dupont Jean"
// "Détails: 30 ans, Paris, Développeur"

8. Classes

ES6 introduced a more intuitive class syntax for object-oriented programming:

// Class definition
class Personne {
  // Constructor
  constructor(nom, age) {
    this.nom = nom;
    this.age = age;
  }
  
  // Methods
  saluer() {
    return `Bonjour, je m'appelle ${this.nom} et j'ai ${this.age} ans.`;
  }
  
  // Static methods
  static creerPersonneAnonymous() {
    return new Personne("Anonyme", 0);
  }
  
  // Getters and setters
  get nomComplet() {
    return this.nom;
  }
  
  set nomComplet(valeur) {
    this.nom = valeur;
  }
}

// Inheritance
class Employe extends Personne {
  constructor(nom, age, poste) {
    super(nom, age); // Call the parent constructor
    this.poste = poste;
  }
  
  saluer() {
    return `${super.saluer()} Je suis ${this.poste}.`;
  }
}

// Usage
const alice = new Personne("Alice", 30);
console.log(alice.saluer()); // "Bonjour, je m'appelle Alice et j'ai 30 ans."

const bob = new Employe("Bob", 35, "Développeur");
console.log(bob.saluer()); // "Bonjour, je m'appelle Bob et j'ai 35 ans. Je suis Développeur."

9. Modules

ES6 standardized JavaScript modules:

// math.js
export const PI = 3.14159;

export function carre(x) {
  return x * x;
}

export default function somme(a, b) {
  return a + b;
}

// main.js
import somme, { PI, carre } from './math.js';

console.log(PI); // 3.14159
console.log(carre(4)); // 16
console.log(somme(2, 3)); // 5

// Import everything
import * as math from './math.js';
console.log(math.PI); // 3.14159
console.log(math.carre(4)); // 16
console.log(math.default(2, 3)); // 5

10. Promises and Async/Await

Promises and Async/Await simplify the handling of asynchronous code:

// Promises
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = { id: 1, nom: "Produit" };
      if (data) {
        resolve(data);
      } else {
        reject("Erreur lors du chargement");
      }
    }, 1000);
  });
}

fetchData()
  .then(data => {
    console.log("Données:", data);
    return data.id;
  })
  .then(id => {
    console.log("ID:", id);
  })
  .catch(error => {
    console.error("Erreur:", error);
  })
  .finally(() => {
    console.log("Opération terminée");
  });

// Promise.all
const promise1 = Promise.resolve(3);
const promise2 = new Promise(resolve => setTimeout(() => resolve("foo"), 100));

Promise.all([promise1, promise2])
  .then(results => {
    console.log(results); // [3, "foo"]
  });

// Async/Await (ES2017)
async function fetchUser() {
  try {
    const response = await fetch('https://api.exemple.com/utilisateurs/1');
    const user = await response.json();
    console.log(user);
    return user;
  } catch (error) {
    console.error("Erreur:", error);
  }
}

// Usage with .then()
fetchUser().then(user => {
  console.log("Utilisateur:", user);
});

Other ES6+ Features

Object Shorthand

const nom = "Alice";
const age = 30;

// Before ES6
const personne1 = {
  nom: nom,
  age: age,
  saluer: function() {
    return "Bonjour !";
  }
};

// With ES6
const personne2 = {
  nom,
  age,
  saluer() {
    return "Bonjour !";
  }
};

Computed Property Names

const cle = "statut";
const valeur = "actif";

const objet = {
  [cle]: valeur,
  [`utilisateur_${valeur}`]: true
};

console.log(objet); // { statut: "actif", utilisateur_actif: true }

Array Methods

const nombres = [1, 2, 3, 4, 5];

// find
const premier = nombres.find(n => n > 2);
console.log(premier); // 3

// findIndex
const index = nombres.findIndex(n => n > 2);
console.log(index); // 2

// includes (ES2016)
console.log(nombres.includes(3)); // true

// Array.from
const divs = document.querySelectorAll('div');
const divsArray = Array.from(divs);

// Array.of
const arr = Array.of(1, 2, 3);
console.log(arr); // [1, 2, 3]

Object Methods

const source = { a: 1, b: 2 };
const cible = { c: 3 };

// Object.assign
const resultat = Object.assign(cible, source);
console.log(resultat); // { a: 1, b: 2, c: 3 }

// Object.entries (ES2017)
console.log(Object.entries(source)); // [["a", 1], ["b", 2]]

// Object.values (ES2017)
console.log(Object.values(source)); // [1, 2]

// Object.fromEntries (ES2019)
const entries = [["a", 1], ["b", 2]];
console.log(Object.fromEntries(entries)); // { a: 1, b: 2 }

Optional Chaining (ES2020)

const utilisateur = {
  nom: "Alice",
  adresse: {
    ville: "Paris"
  }
};

// Before ES2020
const ville1 = utilisateur && utilisateur.adresse && utilisateur.adresse.ville;

// With ES2020
const ville2 = utilisateur?.adresse?.ville;
console.log(ville2); // "Paris"

// With methods
const resultat = utilisateur.getInfo?.();

// With arrays
const premier = utilisateur.amis?.[0];

Nullish Coalescing (ES2020)

// Before ES2020 (problem with 0 and "")
const valeur1 = donnee || "valeur par défaut";

// With ES2020
const valeur2 = donnee ?? "valeur par défaut";

// Difference
console.log(0 || "défaut"); // "défaut"
console.log(0 ?? "défaut"); // 0

console.log("" || "défaut"); // "défaut"
console.log("" ?? "défaut"); // ""

Conclusion

Modern JavaScript features have significantly improved the language, making it more expressive, safer, and more enjoyable to use. These improvements have contributed to JavaScript’s rise as one of the most popular languages in the world.

To stay up to date with the latest features, check the ECMAScript specifications regularly and use tools like Babel to take advantage of new features even in older browsers.

InSkillCoach

About InSkillCoach

Training and technology expert

Coach specializing in advanced technologies and AI, backed by GNeurone Inc.

Certifications:

  • AWS Certified Solutions Architect – Professional
  • Google Cloud certifications
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
846
153

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!