JavaScript Functions as Values and Variables

𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐭𝐫𝐞𝐚𝐭𝐬 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 𝐚𝐬 𝐯𝐚𝐥𝐮𝐞𝐬 — 𝐚𝐧𝐝 𝐭𝐡𝐚𝐭 𝐜𝐡𝐚𝐧𝐠𝐞𝐬 𝐡𝐨𝐰 𝐰𝐞 𝐰𝐫𝐢𝐭𝐞 𝐩𝐫𝐨𝐠𝐫𝐚𝐦𝐬. While revisiting some fundamentals today, I explored how 𝐟𝐢𝐫𝐬𝐭-𝐜𝐥𝐚𝐬𝐬 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 shape the way JavaScript handles behavior and logic. In JavaScript, functions are not just blocks of code. They can be 𝐚𝐬𝐬𝐢𝐠𝐧𝐞𝐝 𝐭𝐨 𝐯𝐚𝐫𝐢𝐚𝐛𝐥𝐞𝐬, 𝐩𝐚𝐬𝐬𝐞𝐝 𝐚𝐬 𝐚𝐫𝐠𝐮𝐦𝐞𝐧𝐭𝐬, and even 𝐫𝐞𝐭𝐮𝐫𝐧𝐞𝐝 𝐟𝐫𝐨𝐦 𝐨𝐭𝐡𝐞𝐫 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬. This ability is what makes functions first-class citizens in the language. This also led me to understand the difference between 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐝𝐞𝐜𝐥𝐚𝐫𝐚𝐭𝐢𝐨𝐧𝐬 and 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐞𝐱𝐩𝐫𝐞𝐬𝐬𝐢𝐨𝐧𝐬. A function declaration is fully hoisted, meaning the function can be invoked even before it appears in the code. But with a function expression, only the variable is hoisted — not the function value itself. Until the assignment happens, the variable holds undefined, which is why calling it early leads to a 𝐓𝐲𝐩𝐞𝐄𝐫𝐫𝐨𝐫. Another interesting concept is 𝐚𝐧𝐨𝐧𝐲𝐦𝐨𝐮𝐬 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬. These are functions𝐰𝐢𝐭𝐡𝐨𝐮𝐭 𝐚 𝐧𝐚𝐦𝐞, typically used when functions are treated as values. When a function expression includes a name, it becomes a 𝐧𝐚𝐦𝐞𝐝 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐞𝐱𝐩𝐫𝐞𝐬𝐬𝐢𝐨𝐧, where the name is accessible only inside the function body. Finally, revisiting 𝐩𝐚𝐫𝐚𝐦𝐞𝐭𝐞𝐫𝐬 𝐯𝐬 𝐚𝐫𝐠𝐮𝐦𝐞𝐧𝐭𝐬 clarified how parameters act as 𝐥𝐨𝐜𝐚𝐥 𝐯𝐚𝐫𝐢𝐚𝐛𝐥𝐞𝐬 𝐢𝐧𝐬𝐢𝐝𝐞 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐬𝐜𝐨𝐩𝐞, receiving the values passed during invocation. Understanding these fundamentals makes it much easier to reason about patterns like callbacks, closures, and asynchronous JavaScript. #JavaScript #SoftwareEngineering #DeveloperJourney #LearningInPublic

To view or add a comment, sign in

Explore content categories