JavaScript ES6+ Features
ES6 (released in 2015) and the yearly versions after it added features that make JavaScript shorter and clearer. Modern code uses them everywhere.
Quick Overview
| Feature | Short example |
|---|---|
let and const | const fee = 5000; |
| Arrow functions | const add = (a, b) => a + b; |
| Template literals | ` Hello ${name} ` |
| Default parameters | function f(x = 1) {} |
| Destructuring | const { name } = student; |
| Spread and rest | [...a, ...b] |
| Optional chaining | user?.address?.city |
| Nullish coalescing | value ?? "default" |
| Classes | class Student {} |
| Modules | import and export |
You already met let, const, arrow functions and template literals. Here are the others.
Destructuring
Destructuring pulls values out of an object or array into variables in one line.
Example
const student = { name: "Hamza", course: "Python", city: "Karachi" };
const { name, course } = student;
console.log(name, course);
const [first, second] = ["Gold", "Silver", "Bronze"];
console.log(first, second);Hamza Python Gold Silver
Spread Operator
Three dots ... spread the items of an array or object into a new one.
Example
const boys = ["Ali", "Usman"];
const girls = ["Sana", "Mehwish"];
const classList = [...boys, ...girls];
const basic = { size: "M", colour: "black" };
const order = { ...basic, colour: "white", qty: 2 };
console.log(classList);
console.log(order);[ 'Ali', 'Usman', 'Sana', 'Mehwish' ]
{ size: 'M', colour: 'white', qty: 2 }Later properties win, so colour becomes "white".
Rest Parameters
In a function, ... collects any number of arguments into an array:
Example
function total(...prices) {
return prices.reduce((sum, p) => sum + p, 0);
}
console.log(total(100, 250, 75)); // 425Optional Chaining and Nullish Coalescing
?. reads a property only if the thing before it exists, instead of throwing an error. ?? gives a fallback when a value is null or undefined.
Example
const user = { name: "Ayesha" };
console.log(user.address?.city); // undefined, no error
console.log(user.address?.city ?? "Unknown"); // Unknown
const stock = 0;
console.log(stock ?? 10); // 0 (?? keeps 0)Classes
A class is a template for creating many objects of the same kind.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
class Student {
constructor(name, marks) {
this.name = name;
this.marks = marks;
}
result() {
return this.marks >= 50 ? "passed" : "needs to try again";
}
}
class Topper extends Student {
result() {
return "topped the class!";
}
}
const students = [new Student("Ali", 72), new Student("Bilal", 41), new Topper("Ayesha", 98)];
document.getElementById("demo").innerHTML =
students.map(s => `${s.name} ${s.result()}`).join("<br>");
</script>
</body>
</html>Try it Yourself »Ali passed Bilal needs to try again Ayesha topped the class!
constructor runs when you write new Student(...). extends creates a class that inherits everything from another class and can change parts of it.
Modules
Modules let you split code into files. One file exports what it shares, another imports it.
Example
// prices.js
export const TAX = 0.17;
export function withTax(price) {
return price + price * TAX;
}Example
// app.js
import { withTax } from "./prices.js";
console.log(withTax(1000)); // 1170To use modules in a page, load the main file with <script type="module" src="app.js"></script>. Modules must be served from a web server, not opened as a local file.
Every modern browser supports these features. Very old browsers do not, but they are now rare.
Exercise
Exercise
What is the value of a after: const [a, b] = [10, 20];
