#javascript #tutorial #intermediate

Day 7: ES6+ Modern Syntax

Day 7: Modern JavaScript (ES6+)

JavaScript got a huge upgrade in 2015 (ES6). If you’re writing code like it’s 2010, you’re working too hard.

1. Destructuring

Unpack values from arrays or objects into distinct variables.

const user = { name: "Jack", age: 30, city: "NYC" };

// Old way
// const name = user.name;
// const age = user.age;

// Modern way
const { name, age } = user;
console.log(name, age); // Jack 30

Arrays:

const colors = ["red", "green"];
const [primary, secondary] = colors;

2. Spread Operator (...)

Expands an array/object into individual elements. Great for copying or merging.

const oldNumbers = [1, 2];
const newNumbers = [...oldNumbers, 3, 4]; 
// [1, 2, 3, 4]

Objects:

const settings = { theme: 'dark', fontSize: 14 };
const userSettings = { ...settings, fontSize: 16 }; 
// { theme: 'dark', fontSize: 16 } (Overrides matches)

3. Template Literals

We saw this in Day 1, but it also supports multi-line strings!

const html = `
    <div>
        <h1>${user.name}</h1>
        <p>Welcome back!</p>
    </div>
`;

4. Modules (Import/Export)

Split code into multiple files.

math.js:

export const add = (a, b) => a + b;
export const pi = 3.14;

main.js:

import { add, pi } from './math.js';
console.log(add(2, 2));

Homework for Day 7:

  1. Create two arrays: fruits and vegetables.
  2. Use the spread operator to combine them into food.
  3. Create a function that takes an object { x: 10, y: 20 } and uses destructuring in the argument list to log x + y.

Day 8: We enter the world of Asynchronous JavaScript!