Unit 7 ยท JavaScript

7.10.5Anonymous functions

An anonymous function has no name. It is created where it is used, usually as an argument (callback) or stored in a variable.

JavaScript
// As a callback to an event listener
window.addEventListener('keydown', function (e) { /* no name */ });

// Arrow function (also anonymous)
coins.forEach(c => c.y += 1);

// Array methods
const alive = enemies.filter(en => en.hp > 0);

// Timer
setInterval(function () { spawnEnemy(); }, 2000);

// Stored in a variable (function expression)
const jump = function () { player.vy = -10; };

// IIFE: Immediately Invoked Function Expression: runs once and keeps variables private
(function () {
  const secret = 'only visible in here';
  console.log('Game starting...');
})();

Why are they useful in games? You write the logic exactly where it is needed (events, timers, filtering lists of enemies and bullets) without cluttering the global scope with throw-away names.