intro-frontend-course

Lecture 3: ES6 Features and Syntax

Introduction to ES6

ECMAScript 2015 (ES6) introduced several new features and syntax improvements to JavaScript, making the language more powerful and easier to work with. Understanding these features is crucial for modern JavaScript development.

1. Let and Const

ES6 introduced two new ways to declare variables: let and const.

Example:

let name = 'John Doe';
name = 'Jane Doe'; // This is allowed

const age = 30;
age = 31; // This will cause an error

Real-World Example: Managing a Shopping Cart

const cart = [];
let totalPrice = 0;

cart.push({ item: 'Laptop', price: 1200 });
totalPrice += 1200;

cart.push({ item: 'Phone', price: 800 });
totalPrice += 800;

console.log(cart);
console.log(totalPrice);

2. Arrow Functions

Arrow functions provide a shorter syntax for writing functions and also handle the this keyword differently compared to traditional functions.

Example:

const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

Real-World Example: Filtering an Array

const products = [
  { name: 'Laptop', price: 1200 },
  { name: 'Phone', price: 800 },
  { name: 'Tablet', price: 600 }
];

const affordableProducts = products.filter(product => product.price < 1000);
console.log(affordableProducts); // [{ name: 'Phone', price: 800 }, { name: 'Tablet', price: 600 }]

3. Template Literals

Template literals allow for easier string interpolation using backticks and ${} syntax.

Example:

const name = 'John Doe';
const greeting = `Hello, my name is ${name}`;
console.log(greeting); // Hello, my name is John Doe

Real-World Example: Creating a Product Description

const product = { name: 'Laptop', price: 1200 };
const description = `The ${product.name} costs $${product.price}.`;
console.log(description); // The Laptop costs $1200.

4. Destructuring

Destructuring allows for extracting values from arrays or properties from objects into distinct variables.

Example:

const person = { name: 'John Doe', age: 30 };
const { name, age } = person;
console.log(name); // John Doe
console.log(age); // 30

Real-World Example: Extracting Data from an API Response

const response = {
  user: { id: 1, name: 'John Doe' },
  posts: [{ id: 1, title: 'Hello World' }, { id: 2, title: 'JavaScript Rocks' }]
};

const { user, posts } = response;
console.log(user.name); // John Doe
console.log(posts[0].title); // Hello World

5. Default Parameters

Default parameters allow you to set default values for function parameters.

Example:

function greet(name = 'Guest') {
  console.log(`Hello, ${name}`);
}

greet(); // Hello, Guest
greet('John'); // Hello, John

Real-World Example: Creating a Discount Function

const calculateDiscount = (price, discount = 0.1) => price - (price * discount);

console.log(calculateDiscount(100)); // 90
console.log(calculateDiscount(100, 0.2)); // 80

6. Spread and Rest Operators

The spread operator (...) allows an iterable to expand in places where multiple arguments or elements are expected. The rest operator collects multiple elements and condenses them into a single array.

Example:

const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];
console.log(newArr); // [1, 2, 3, 4, 5]

const sum = (...numbers) => numbers.reduce((acc, num) => acc + num, 0);
console.log(sum(1, 2, 3)); // 6

Real-World Example: Combining Arrays

const fruits = ['Apple', 'Banana'];
const vegetables = ['Carrot', 'Broccoli'];

const shoppingList = [...fruits, ...vegetables];
console.log(shoppingList); // ['Apple', 'Banana', 'Carrot', 'Broccoli']

7. Classes

ES6 classes provide a clear and concise way to create objects and deal with inheritance.

Example:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const john = new Person('John Doe', 30);
john.greet(); // Hello, my name is John Doe and I am 30 years old.

Real-World Example: Extending a Product Class

class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  display() {
    console.log(`${this.name} costs $${this.price}`);
  }
}

class DiscountedProduct extends Product {
  constructor(name, price, discount) {
    super(name, price);
    this.discount = discount;
  }

  display() {
    const discountedPrice = this.price * (1 - this.discount);
    console.log(`${this.name} costs $${discountedPrice} after discount`);
  }
}

const laptop = new DiscountedProduct('Laptop', 1200, 0.1);
laptop.display(); // Laptop costs $1080 after discount

8. Modules

ES6 modules allow you to export and import code between different files.

Example:

// in file math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// in file app.js
import { add, subtract } from './math.js';

console.log(add(2, 3)); // 5
console.log(subtract(5, 3)); // 2

Real-World Example: Using Modules in a Shopping Cart

// in file cart.js
export class Cart {
  constructor() {
    this.items = [];
  }

  addItem(item) {
    this.items.push(item);
  }

  getTotal() {
    return this.items.reduce((total, item) => total + item.price, 0);
  }
}

// in file app.js
import { Cart } from './cart.js';

const cart = new Cart();
cart.addItem({ name: 'Laptop', price: 1200 });
cart.addItem({ name: 'Phone', price: 800 });

console.log(cart.getTotal()); // 2000

Video Resources:

By mastering these ES6 features and syntax, you will be able to write more efficient, readable, and maintainable JavaScript code, allowing you to build complex applications with ease.