ES6+ Features

Menguasai fitur-fitur modern JavaScript ES6+ yang wajib dikuasai developer masa kini

ES6 (ECMAScript 2015) membawa revolusi besar dalam JavaScript. Chapter ini membahas fitur-fitur utama yang mengubah cara kita menulis JavaScript.

Arrow Functions

Arrow functions memberikan sintaks yang lebih concise untuk menulis functions.

// Traditional function
function add(a, b) {
    return a + b;
}

// Arrow function
const add = (a, b) => a + b;

// Arrow function dengan multiple statements
const greet = (name) => {
    const message = `Hello, ${name}!`;
    return message.toUpperCase();
};

// Arrow function tanpa parameter
const getRandom = () => Math.random();

// Arrow function dengan satu parameter (tanpa parentheses)
const double = x => x * 2;

Lexical this Binding

class Timer {
    constructor() {
        this.seconds = 0;
    }
    
    start() {
        // Arrow function menjaga context 'this'
        setInterval(() => {
            this.seconds++;
            console.log(this.seconds);
        }, 1000);
    }
}

const timer = new Timer();
timer.start();

Template Literals

Template literals memungkinkan string interpolation dan multi-line strings.

const name = 'John';
const age = 30;

// String interpolation
const greeting = `Hello, my name is ${name} and I'm ${age} years old.`;

// Multi-line strings
const html = `
    <div class="card">
        <h2>${name}</h2>
        <p>Age: ${age}</p>
    </div>
`;

// Expression dalam template literals
const price = 100;
const tax = 0.1;
const total = `Total: $${(price * (1 + tax)).toFixed(2)}`;

Tagged Template Literals

function highlight(strings, ...values) {
    return strings.reduce((result, string, i) => {
        const value = values[i] ? `<mark>${values[i]}</mark>` : '';
        return result + string + value;
    }, '');
}

const name = 'JavaScript';
const feature = 'awesome';
const message = highlight`${name} is ${feature}!`;
// Result: "<mark>JavaScript</mark> is <mark>awesome</mark>!"

Destructuring

Destructuring memungkinkan ekstraksi values dari arrays dan objects.

Array Destructuring

const numbers = [1, 2, 3, 4, 5];

// Basic destructuring
const [first, second] = numbers;
console.log(first, second); // 1, 2

// Skip elements
const [, , third] = numbers;
console.log(third); // 3

// Rest operator
const [head, ...tail] = numbers;
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]

// Default values
const [a, b, c = 0] = [1, 2];
console.log(c); // 0

Object Destructuring

const person = {
    name: 'Alice',
    age: 28,
    city: 'Jakarta',
    country: 'Indonesia'
};

// Basic destructuring
const { name, age } = person;
console.log(name, age); // Alice, 28

// Rename variables
const { name: fullName, age: years } = person;
console.log(fullName, years); // Alice, 28

// Default values
const { height = 170 } = person;
console.log(height); // 170

// Nested destructuring
const user = {
    id: 1,
    profile: {
        name: 'Bob',
        settings: {
            theme: 'dark'
        }
    }
};

const { profile: { name: userName, settings: { theme } } } = user;
console.log(userName, theme); // Bob, dark

Spread and Rest Operators

Spread Operator (…)

// Array spreading
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

// Object spreading
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 }

// Function arguments
function sum(a, b, c) {
    return a + b + c;
}

const numbers = [1, 2, 3];
console.log(sum(...numbers)); // 6

// Copy arrays/objects
const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];

const originalObject = { name: 'John' };
const copiedObject = { ...originalObject };

Rest Operator

// Function parameters
function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

// Object rest
const { name, ...otherProps } = person;
console.log(otherProps); // { age: 28, city: 'Jakarta', country: 'Indonesia' }

Enhanced Object Literals

const name = 'Alice';
const age = 25;

// Property shorthand
const person = { name, age }; // sama dengan { name: name, age: age }

// Method shorthand
const calculator = {
    // Old way
    add: function(a, b) {
        return a + b;
    },
    
    // New way
    subtract(a, b) {
        return a - b;
    },
    
    // Computed property names
    ['multiply'](a, b) {
        return a * b;
    }
};

// Dynamic property names
const propertyName = 'color';
const car = {
    brand: 'Toyota',
    [propertyName]: 'red',
    [`${propertyName}Code`]: '#FF0000'
};

Default Parameters

// Basic default parameters
function greet(name = 'Guest', greeting = 'Hello') {
    return `${greeting}, ${name}!`;
}

console.log(greet()); // "Hello, Guest!"
console.log(greet('Alice')); // "Hello, Alice!"
console.log(greet('Bob', 'Hi')); // "Hi, Bob!"

// Default parameters dengan expressions
function createUser(name, role = 'user', id = generateId()) {
    return { name, role, id };
}

// Default parameters dengan destructuring
function processData({ 
    input = [], 
    format = 'json', 
    validate = true 
} = {}) {
    // Process data
}

Let and Const

// var vs let
function varExample() {
    for (var i = 0; i < 3; i++) {
        setTimeout(() => console.log(i), 100); // 3, 3, 3
    }
}

function letExample() {
    for (let i = 0; i < 3; i++) {
        setTimeout(() => console.log(i), 100); // 0, 1, 2
    }
}

// const untuk immutable bindings
const API_URL = 'https://api.example.com';
// API_URL = 'new-url'; // Error!

const user = { name: 'Alice' };
user.name = 'Bob'; // OK, object masih bisa dimodifikasi
user.age = 25; // OK

// Tapi tidak bisa reassign
// user = { name: 'Charlie' }; // Error!

Fitur-fitur ES6+ ini membuat JavaScript lebih powerful dan expressive. Di chapter selanjutnya, kita akan mempelajari tentang Promises dan async/await untuk handling asynchronous operations.