Chapter 8

Control Flow

Learning Objectives

  • Use if/else for conditional logic
  • Implement loops for repetition
  • Combine conditions with logical operators
  • See how MixMind makes decisions

If/Else Statements

// Basic if statement
if (bpm > 140) {
    console.log("Fast tempo");
}

// if/else
if (bpm > 140) {
    console.log("Fast");
} else {
    console.log("Normal or slow");
}

// if/else if/else
if (bpm > 140) {
    console.log("Fast");
} else if (bpm > 100) {
    console.log("Medium");
} else {
    console.log("Slow");
}

// Comparison operators
// == equal (loose)
// === equal (strict, preferred)
// != not equal
// !== not equal (strict)
// >, <, >=, <=

Logical Operators

// AND (&&) - both must be true
if (bpm > 120 && key === "Am") {
    console.log("Compatible");
}

// OR (||) - at least one must be true
if (bpm > 140 || energy > 0.8) {
    console.log("High energy track");
}

// NOT (!) - reverses the condition
if (!isPlaying) {
    startPlayback();
}

// Combining conditions
if ((bpm > 120 && bpm < 140) || (key === "Am" || key === "C")) {
    console.log("Good match");
}

Loops

// for loop
for (let i = 0; i < tracks.length; i++) {
    analyzeTrack(tracks[i]);
}

// for...of (modern, preferred for arrays)
for (let track of tracks) {
    analyzeTrack(track);
}

// while loop
let attempts = 0;
while (attempts < 3) {
    if (tryConnect()) break;
    attempts++;
}

// Loop control
for (let track of tracks) {
    if (track.bpm < 100) continue; // Skip this one
    if (track.duration > 600) break; // Stop loop
    processTrack(track);
}

🎵 MixMind Connection

How MixMind Uses Control Flow

// Transition decision making
function chooseTransition(track1, track2) {
    const bpmDiff = Math.abs(track1.bpm - track2.bpm);
    const keysCompatible = areKeysCompatible(track1.key, track2.key);
    
    if (bpmDiff < 5 && keysCompatible) {
        return "smooth_blend";
    } else if (bpmDiff < 10) {
        return "eq_fade";
    } else {
        return "hard_cut";
    }
}

// Processing all tracks
for (let track of library) {
    if (!track.analyzed) {
        await analyzeTrack(track);
        track.analyzed = true;
    }
}

// Energy-based filtering
const highEnergy = tracks.filter(t => t.energy > 0.7);

Exercise 8.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.