Загрузка...

Anonymous Functions | JavaScript Fundamentals Series

Up until now, every function you have written has had a name or an alias stored in a constant so that it could be reused later. A true anonymous function has no name and no alias. It is written completely in-place directly where it is needed, executed once, and immediately discarded by the computer's memory.

While writing an anonymous function and forcing it to run instantly using an Immediately Invoked Function Expression (IIFE) looks a bit strange, the true professional power of anonymous functions shines when we use them as callbacks—passing them as inputs into other functions like setTimeout().

When you pass a function definition into another function, you are handing over a recipe to be cooked later, rather than the finished meal.

Key Takeaways:
- The Garbage Collection Benefit: Because an inline anonymous function isn't tied to a variable name, JavaScript automatically purges it from memory the moment it finishes running, keeping your application incredibly lean.
- Asynchronous Timing & The Race Condition: setTimeout(callback, delay) expects a function reference as its first argument and a delay in milliseconds as its second.
- Non-Blocking Execution: Multiple setTimeout timers run independently in the background. If you start a 3-second timer and a 5-second timer back-to-back, the second one will fire exactly 2 seconds after the first, because their countdowns started at virtually the same moment.

The Execution Distinction: Never put invocation parentheses () on a function name when passing it into setTimeout (e.g., use setTimeout(blastOff, 3000), not blastOff()). If you include the parentheses, the function fires immediately instead of waiting for the timer.

Watch the video to see how we choreograph staggered rocket launch sequences using asynchronous timers, then head over to the practice lab to wire up your own single-use, timed arrow engines!

DEMO CODE & PRACTICE EXERCISES:
https://github.com/CodeWithCarrie/javascript-fundamentals/blob/main/tutorials/09-more-functions/anonymous-functions

00:00 Introduction to Anonymous Functions
00:53 Creating and Invoking an IIFE (In-Place Execution)
01:45 When to Use Reusable vs. Anonymous Functions
02:15 Asynchronous Execution with setTimeout()
03:15 Writing Anonymous Callbacks In-Place
04:18 Debugging Overlapping Timers & Race Conditions
05:41 Wrap-Up & Next Steps

Видео Anonymous Functions | JavaScript Fundamentals Series канала Code with Carrie
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять