JavaScript Tutorial menu

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

FeatureShort example
let and constconst fee = 5000;
Arrow functionsconst add = (a, b) => a + b;
Template literals` Hello ${name} `
Default parametersfunction f(x = 1) {}
Destructuringconst { name } = student;
Spread and rest[...a, ...b]
Optional chaininguser?.address?.city
Nullish coalescingvalue ?? "default"
Classesclass Student {}
Modulesimport 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

javascript
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);
Output
Hamza Python
Gold Silver

Spread Operator

Three dots ... spread the items of an array or object into a new one.

Example

javascript
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);
Output
[ '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

javascript
function total(...prices) {
  return prices.reduce((sum, p) => sum + p, 0);
}
console.log(total(100, 250, 75));   // 425

Optional 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

javascript
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

html
<!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 »
Output
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

javascript
// prices.js
export const TAX = 0.17;
export function withTax(price) {
  return price + price * TAX;
}

Example

javascript
// app.js
import { withTax } from "./prices.js";
console.log(withTax(1000));   // 1170

To 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];

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp