Chapter 12

ES6+ Modern JavaScript

Learning Objectives

  • Learn modern JavaScript features
  • Use destructuring and spread operators
  • Work with modules
  • Apply modern best practices

Arrow Functions

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

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

// With body
const process = (data) => {
    const result = transform(data);
    return result;
};

// Single parameter (no parentheses needed)
const double = x => x * 2;

// No parameters
const getRandom = () => Math.random();

Destructuring

// Object destructuring
const track = { title: "Song", bpm: 128, key: "Am" };
const { title, bpm, key } = track;
console.log(title); // "Song"

// With renaming
const { title: trackTitle, bpm: tempo } = track;

// Array destructuring
const [first, second, third] = [1, 2, 3];
console.log(first); // 1

// Function parameters
function displayTrack({ title, bpm, key }) {
    console.log(`${title} - ${bpm} BPM - ${key}`);
}

// Default values
const { volume = 100, muted = false } = settings;

Spread & Rest Operators

// Spread - expand arrays/objects
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

// Merge objects
const defaults = { volume: 100, muted: false };
const userSettings = { volume: 80 };
const settings = { ...defaults, ...userSettings };

// Rest - collect remaining items
function logArgs(first, ...rest) {
    console.log(first); // First argument
    console.log(rest); // Array of remaining
}

// In function parameters
const sum = (...numbers) => {
    return numbers.reduce((total, n) => total + n, 0);
};

Template Literals

// String interpolation
const name = "MixMind";
const version = 2;
const message = `Welcome to ${name} v${version}`;

// Multi-line strings
const html = `
    <div class="card">
        <h3>${track.title}</h3>
        <p>${track.bpm} BPM</p>
    </div>
`;

// Expressions
const price = `Total: $${(quantity * price).toFixed(2)}`;

Modules

// Export from a file (audio.js)
export function detectBPM(buffer) {
    // ...
}

export const SAMPLE_RATE = 44100;

export class AudioAnalyzer {
    // ...
}

// Default export
export default function analyze(buffer) {
    // ...
}

// Import in another file
import analyze, { detectBPM, SAMPLE_RATE } from './audio.js';
import { AudioAnalyzer } from './audio.js';

// Import all
import * as Audio from './audio.js';
Audio.detectBPM(buffer);

🎵 MixMind Connection

Modern JavaScript in MixMind

// Destructuring analysis results
const { bpm, key, energy, sections } = await analyzeTrack(file);

// Spread for settings
const defaultSettings = { crossfade: 8, format: "mp3" };
const settings = { ...defaultSettings, ...userPreferences };

// Template literals for UI
function createTrackCard(track) {
    return `
        <div class="track-card" data-id="${track.id}">
            <h3>${track.title}</h3>
            <p>${track.bpm} BPM | ${track.key}</p>
            <div class="energy" style="width: ${track.energy * 100}%"></div>
        </div>
    `;
}

// Modules for organization
import { detectBPM, detectKey } from './analysis.js';
import { AudioEngine } from './audio-engine.js';
import { StemSeparator } from './stems.js';

// Async/await with modern features
async function processLibrary(files) {
    const results = await Promise.all(
        files.map(async (file) => {
            const buffer = await loadAudio(file);
            const analysis = await analyze(buffer);
            return { file, ...analysis };
        })
    );
    return results;
}

Exercise 12.1: Practice

Goal: Apply what you've learned in this chapter

Try the concepts from this chapter in your browser's console or a simple HTML file. Experiment with the code examples and modify them to see what happens.

📝 Quick Reference:

Review the key concepts from this chapter and make sure you understand each one before moving to the next chapter.