Script Valley
JavaScript Tutorial for Beginners to Advanced
ES6+ Modern JavaScript FeaturesLesson 6.2

ES6+ Template Literals, Modules, and Classes

template literals, tagged templates, ES6 modules (import/export), class syntax, constructor, inheritance, getters/setters

ES6+ Template Literals, Modules, and Classes

This lesson covers three more pillars of modern JavaScript: template literals for clean string formatting, modules for organising code across files, and classes for object-oriented programming patterns.

Template Literals

const name = 'Alice';
const score = 95;

// Multi-line string
const report = `
  Student Report
  Name: ${name}
  Score: ${score}%
  Grade: ${score >= 90 ? 'A' : 'B'}
`;

console.log(report);

// Expression interpolation
console.log(`${2 + 2} is four`);
console.log(`Today is ${new Date().toDateString()}`);

ES6 Modules

// math.js
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }
export default function subtract(a, b) { return a - b; }

// app.js
import subtract, { PI, add, multiply } from './math.js';

console.log(PI);              // 3.14159
console.log(add(2, 3));       // 5
console.log(subtract(10, 4)); // 6

ES6 Classes

class Animal {
  constructor(name, sound) {
    this.name = name;
    this.sound = sound;
  }

  speak() {
    return `${this.name} says ${this.sound}!`;
  }

  get info() {
    return `${this.name} (${this.sound})`;
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name, 'Woof');
    this.tricks = [];
  }

  learn(trick) {
    this.tricks.push(trick);
  }

  showTricks() {
    return `${this.name} knows: ${this.tricks.join(', ')}`;
  }
}

const dog = new Dog('Rex');
dog.learn('sit');
dog.learn('shake');
console.log(dog.speak());      // 'Rex says Woof!'
console.log(dog.showTricks()); // 'Rex knows: sit, shake'
console.log(dog.info);         // 'Rex (Woof)'

ES6+ Template Literals, Modules, and Classes — ES6+ Modern JavaScript Features — JavaScript Tutorial for Beginners to Advanced — Script Valley — Script Valley