JavaScript Function Declarations vs Expressions

𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝗶𝗽: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 𝘃𝘀 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 Both are common ways to write functions in JavaScript, but they behave differently under the hood 👇 // 𝘍𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘋𝘦𝘤𝘭𝘢𝘳𝘢𝘵𝘪𝘰𝘯 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘨𝘳𝘦𝘦𝘵() {  𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘏𝘦𝘭𝘭𝘰"); } // 𝘍𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘌𝘹𝘱𝘳𝘦𝘴𝘴𝘪𝘰𝘯 𝘤𝘰𝘯𝘴𝘵 𝘨𝘳𝘦𝘦𝘵 = 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 () {  𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘏𝘦𝘭𝘭𝘰"); }; 𝗞𝗲𝘆 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲𝘀 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴  • Function declarations are available before they appear in the code  • Function expressions are not 𝘨𝘳𝘦𝘦𝘵(); // 𝘸𝘰𝘳𝘬𝘴 𝘰𝘯𝘭𝘺 𝘸𝘪𝘵𝘩 𝘥𝘦𝘤𝘭𝘢𝘳𝘢𝘵𝘪𝘰𝘯 𝗦𝗰𝗼𝗽𝗲 & 𝗙𝗹𝗲𝘅𝗶𝗯𝗶𝗹𝗶𝘁𝘆  • Declarations are great for defining reusable, top-level logic  • Expressions work well for callbacks, closures, and conditional behaviour 𝘤𝘰𝘯𝘴𝘵 𝘩𝘢𝘯𝘥𝘭𝘦𝘳 = 𝘪𝘴𝘔𝘰𝘣𝘪𝘭𝘦  ? 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘮𝘰𝘣𝘪𝘭𝘦𝘏𝘢𝘯𝘥𝘭𝘦𝘳() {}  : 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘥𝘦𝘴𝘬𝘵𝘰𝘱𝘏𝘢𝘯𝘥𝘭𝘦𝘳() {}; 𝗡𝗮𝗺𝗲𝗱 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀 (𝗹𝗲𝘀𝘀 𝗸𝗻𝗼𝘄𝗻) 𝘤𝘰𝘯𝘴𝘵 𝘨𝘳𝘦𝘦𝘵 = 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘴𝘢𝘺𝘏𝘦𝘭𝘭𝘰() {  𝘴𝘢𝘺𝘏𝘦𝘭𝘭𝘰(); // 𝘢𝘤𝘤𝘦𝘴𝘴𝘪𝘣𝘭𝘦 𝘩𝘦𝘳𝘦 }; 𝘴𝘢𝘺𝘏𝘦𝘭𝘭𝘰(); // 𝘯𝘰𝘵 𝘢𝘤𝘤𝘦𝘴𝘴𝘪𝘣𝘭𝘦 𝘩𝘦𝘳𝘦 👉 In named function expressions, the function name exists 𝗼𝗻𝗹𝘆 𝗶𝗻𝘀𝗶𝗱𝗲 𝘁𝗵𝗲 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗶𝘁𝘀𝗲𝗹𝗳. This keeps the outer scope clean while still allowing recursion and better debugging. 𝗪𝗵𝗲𝗻 𝘁𝗼 𝘂𝘀𝗲 𝘄𝗵𝗮𝘁? Function Declarations → shared utilities, clearer structure Function Expressions → dynamic logic, event handlers Arrow Functions → concise syntax for simple callbacks 📌 Small details like these make your JavaScript more predictable and maintainable. If this helped, feel free to share or add your thoughts 👇 #JavaScript #WebDevelopment #Frontend #ProgrammingTips #Learning

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories