𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝗶𝗽: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 𝘃𝘀 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 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
JavaScript Function Declarations vs Expressions
More Relevant Posts
-
🤔 Ever wondered why arrow functions behave differently from normal functions in JavaScript? They look shorter, but they change the rules. 🧠 JavaScript interview question What are arrow functions and how are they different from normal functions? ✅ Short answer • Arrow functions are a shorter ES6 syntax • They do not have their own this • They are not constructors • They don’t have arguments, prototype, or new.target 🔍 A bit more detail 👉 Lexical this (the big one) Arrow functions capture this from where they are defined, not how they’re called. const obj = { count: 0, inc() { setTimeout(() => { this.count++; }, 100); } }; No .bind(this) needed. The arrow keeps the outer this. 👉 No own arguments Use rest parameters instead: const sum = (...nums) => nums.reduce((a, b) => a + b, 0); 👉 Not constructible new (() => {}) // ❌ TypeError Arrow functions have no prototype and can’t be used with new. 👉 Implicit returns const double = x => x * 2; Block body? You must return. ⚠️ When to avoid arrow functions • Object or prototype methods that rely on dynamic this • Constructors or generator functions • Event handlers that expect this to be the DOM element const obj = { total: 0, add() { this.total++; // ✅ correct } }; 🚀 When arrow functions shine • Callbacks (setTimeout, promises) • Array methods (map, filter, reduce) • Short utility functions • Preserving outer this in classes 🧩 Mental checklist • Need your own this? → normal function • Need outer this? → arrow function • Need new, arguments, or prototype? → normal function 💡 Arrow functions aren’t just shorter syntax, they change semantics. #javascript #frontend #webdevelopment #react #interviewprep #programming
To view or add a comment, sign in
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟴 Have you ever seen JavaScript behave correctly… but still give the wrong output? 🤔 𝘉𝘦𝘧𝘰𝘳𝘦 𝘴𝘤𝘳𝘰𝘭𝘭𝘪𝘯𝘨, 𝘨𝘶𝘦𝘴𝘴 𝘵𝘩𝘦 𝘰𝘶𝘵𝘱𝘶𝘵 𝘰𝘧 𝘵𝘩𝘪𝘴 𝘴𝘪𝘮𝘱𝘭𝘦 𝘤𝘰𝘥𝘦 𝚏𝚘𝚛 (𝚟𝚊𝚛 𝚒 = 𝟷; 𝚒 <= 𝟹; 𝚒++) { 𝚜𝚎𝚝𝚃𝚒𝚖𝚎𝚘𝚞𝚝(() => { 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚒); }, 𝟷𝟶𝟶𝟶); } 𝗘𝘅𝗽𝗹𝗲𝗰𝘁𝗲𝗱 1, 2, 3 𝗔𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗿𝗲𝘀𝘂𝗹𝘁 4,4,4 𝗧𝗵𝗶𝘀 𝗶𝘀 𝗮 𝗰𝗹𝗼𝘀𝘂𝗿𝗲 𝗯𝘂𝗴 — 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗰𝗼𝗺𝗺𝗼𝗻 (𝗮𝗻𝗱 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗻𝗴) 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗽𝗶𝘁𝗳𝗮𝗹𝗹𝘀. 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗛𝗮𝗽𝗽𝗲𝗻𝘀 • var is function-scoped • setTimeout creates a closure • All callbacks reference the same variable i • When they execute, the loop has already finished Closures don’t capture values — they capture references. 𝗧𝗵𝗲 𝗙𝗶𝘅 𝚏𝚘𝚛 (𝚕𝚎𝚝 𝚒 = 𝟷; 𝚒 <= 𝟹; 𝚒++) { 𝚜𝚎𝚝𝚃𝚒𝚖𝚎𝚘𝚞𝚝(() => { 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚒); }, 𝟷𝟶𝟶𝟶); } 𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝘄𝗼𝗿𝗸𝘀: • let is block-scoped • Each iteration gets its own binding • Each closure remembers a different i 𝗬𝗼𝘂’𝗹𝗹 𝘀𝗲𝗲 𝘁𝗵𝗶𝘀 𝗽𝗮𝘁𝘁𝗲𝗿𝗻 𝗶𝗻: • Event handlers • Async loops • API callbacks • Timers • React effects If you don’t understand closures, You don’t see the bug — you just debug longer. #JavaScript #JSFundamentals #Closures #FrontendDevelopment #WebDevelopment #BugFixing #ReactJS #LearningInPublic
To view or add a comment, sign in
-
-
🚀 5 Tricky JavaScript Output Questions (Closures & Scope) Let’s test your JS fundamentals 👇 Try to guess the output before checking answers. 1️⃣ for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 2️⃣ let a = 10; (function () { console.log(a); let a = 20; })(); 3️⃣ function foo() { console.log(x); var x = 10; } foo(); 4️⃣ const obj = { a: 10, getA() { return this.a; } }; const fn = obj.getA; console.log(fn()); 5️⃣ console.log(typeof typeof 1); Answers below 👇 1️⃣ 3 3 3 (var is function-scoped, same reference) 2️⃣ ReferenceError (Temporal Dead Zone for `let`) 3️⃣ undefined (var hoisting without initialization) 4️⃣ undefined (`this` is lost when function is detached) 5️⃣ "string" (typeof 1 → "number", typeof "number" → "string") If you can explain *why*, you’re interview-ready 💯 #javascript #frontend #interviewprep #webdevelopment
To view or add a comment, sign in
-
🧠 99% of JavaScript devs get this event loop question wrong 👀 (Even seniors pause before answering) No frameworks. No libraries. Just how JavaScript actually schedules work. 🧩 Output-Based Question (Event Loop: sync vs microtasks vs macrotasks) console.log("start"); setTimeout(() => { console.log("timeout"); }, 0); Promise.resolve().then(() => { console.log("promise"); }); (async function () { console.log("async"); })(); console.log("end"); ❓ What will be printed — in the correct order? ❌ Don’t run the code 🧠 Think like the JavaScript engine A. start → async → end → promise → timeout B. start → end → async → promise → timeout C. start → async → promise → end → timeout D. start → promise → async → end → timeout 👇 Drop your answer in the comments (no cheating 😄) Why this question matters This tests whether you truly understand: • synchronous execution • the event loop • microtasks vs macrotasks • why Promise.then beats setTimeout(0) • async IIFEs vs promises Many developers “use” async code every day — but few understand when it actually runs. Good JavaScript developers don’t memorize outputs. They understand how the engine thinks. 💡 I’ll pin the full explanation after a few answers. #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #ProgrammingFundamentals #InterviewPrep #MCQ #DeveloperTips #CodeQuality
To view or add a comment, sign in
-
-
Ever wondered what happens BEHIND THE SCENES when your JavaScript code runs? 🚀 Let me break it down for you! 👇 ❌ Why variables show "undefined" ❌ How functions get called ❌ What "hoisting" really means ❌ Why my code executes in a certain order Then I learned about EXECUTION CONTEXT, and everything clicked! 💡 Here's what happens when this simple code runs: ``` var a = 10; var b = 20; function greet() { var name = "Alice"; console.log("Hello", name); } greet(); ``` 🔄 THE PROCESS: 1️⃣ MEMORY CREATION PHASE → JavaScript scans the code FIRST → Variables get "undefined" → Functions get their full definition → This is why hoisting works! 2️⃣ EXECUTION PHASE → Code runs line by line → Variables get actual values (a=10, b=20) → Functions are invoked 3️⃣ CALL STACK → Manages execution contexts → Works like a stack of plates (LIFO - Last In, First Out) → Each function call creates a NEW context → When function completes, context is removed 🎯 WHY THIS MATTERS: Understanding execution context helps you: ✅ Debug "undefined" errors easily ✅ Master closures and scope ✅ Write more efficient code ✅ Ace technical interviews ✅ Understand async behavior better I've created a detailed guide with visual diagrams explaining the entire process step-by-step! 📄 Check out the attached document for: • Complete execution flow breakdown • Visual representations • Real code examples • Key takeaways 💬 What JavaScript concept confused you the most as a beginner? Drop a comment below! P.S. If you found this helpful, give it a ❤️ and share with someone learning JavaScript! #JavaScript #WebDevelopment #Programming #LearnToCode #CodingTips #ExecutionContext #CallStack #DeveloperCommunity #SoftwareDevelopment #FrontendDevelopment #JavaScriptTips #CodingForBeginners #WebDevTips #TechLearning
To view or add a comment, sign in
-
🏹 𝐓𝐡𝐞 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐅𝐚𝐜𝐞-𝐎𝐟𝐟: 𝐀𝐫𝐫𝐨𝐰 vs. 𝐑𝐞𝐠𝐮𝐥𝐚𝐫 If the this keyword feels like a riddle wrapped in a mystery, you aren’t alone! It’s one of the most confusing parts of JavaScript, but the secret lies in how you define your functions. Here is the breakdown of the two heavyweights and exactly when to use them: 1. 𝐑𝐞𝐠𝐮𝐥𝐚𝐫 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 (𝐓𝐡𝐞 𝐃𝐲𝐧𝐚𝐦𝐢𝐜 𝐃𝐮𝐨) 🔄 𝐒𝐲𝐧𝐭𝐚𝐱: function doSomething() { ... } 𝐓𝐡𝐞 '𝐭𝐡𝐢𝐬' 𝐁𝐞𝐡𝐚𝐯𝐢𝐨𝐫: It is dynamic. The value of this depends entirely on how the function is called (the caller). 𝐁𝐞𝐬𝐭 𝐅𝐨𝐫: Object methods or constructor functions where you need to access the object's own properties. 𝐓𝐡𝐞 𝐋𝐞𝐬𝐬𝐨𝐧: Use these when you want the function to have its own context. 2. 𝐀𝐫𝐫𝐨𝐰 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 (𝐓𝐡𝐞 𝐒𝐥𝐞𝐞𝐤 𝐒𝐡𝐚𝐫𝐩𝐬𝐡𝐨𝐨𝐭𝐞𝐫) 🎯 𝐒𝐲𝐧𝐭𝐚𝐱: const doSomething = () => { ... } 𝐓𝐡𝐞 '𝐭𝐡𝐢𝐬' 𝐁𝐞𝐡𝐚𝐯𝐢𝐨𝐫: It is lexical. They don’t have their own this. Instead, they "inherit" it from the surrounding code (the parent scope). 𝐁𝐞𝐬𝐭 𝐅𝐨𝐫: Callbacks (like .map() or .filter()), closures, and preserving context inside setTimeout. 𝐓𝐡𝐞 𝐋𝐞𝐬𝐬𝐨𝐧: Use these to keep your code concise and to avoid the "that = this" or .bind(this) hacks of the past. 🚩 𝐖𝐡𝐞𝐧 𝐍𝐎𝐓 𝐭𝐨 𝐮𝐬𝐞 𝐀𝐫𝐫𝐨𝐰 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬: Methods in Objects: If you use an arrow function as an object method, this will point to the global window/undefined instead of the object itself! Event Listeners: If you need this to represent the element that was clicked, stick to a regular function. 𝐓𝐡𝐞 𝐆𝐨𝐥𝐝𝐞𝐧 𝐑𝐮𝐥𝐞: Use Arrow Functions by default for their clean syntax and predictable context in callbacks. Switch to Regular Functions only when you specifically need a dynamic this (like in methods or constructors). Are you still using .bind(this) in 2026, or have you fully embraced the arrow? Let’s settle the debate below! 👇 #JavaScript #CodingTips #WebDev #SoftwareEngineering #ArrowFunctions #ProgrammingLogic #CleanCode
To view or add a comment, sign in
-
Today I explored one of the most powerful combinations in JavaScript: setTimeout() and Closures. I always knew about them, but now I truly understand how crucial they are in building asynchronous and dynamic applications. setTimeout() is not just a delay function. It shows how JavaScript handles: Asynchronous execution The event loop Non-blocking behavior Closures explain how functions remember their surrounding scope, even after execution is completed. When combined with setTimeout(), they form the foundation of many real-world features like timers, animations, background tasks, and delayed API calls. Example: function greet() { let name = "JavaScript"; setTimeout(function () { console.log(name); }, 2000); } greet(); Even after greet() finishes execution, the inner function still remembers name. That is the power of closure. Advantages: Enables asynchronous and non-blocking operations Makes delayed execution simple and effective Closures allow data privacy and memory persistence Essential for real-time features, animations, and background jobs Forms the backbone of callbacks and async programming Disadvantages / Cautions: Overuse of closures can increase memory usage Poor handling can lead to memory leaks Complex nested callbacks reduce readability Debugging asynchronous code requires strong fundamentals 💡 Key takeaway: setTimeout() shows when code runs. Closures decide what data that code can access. Together, they demonstrate how JavaScript manages time, memory, and execution context. Understanding this moves JavaScript from simple scripting to real engineering. This session helped me understand how asynchronous programming truly works internally and why closures are one of the most important concepts in JavaScript. #JavaScript #SetTimeout #Closures #AsyncProgramming #EventLoop #WebDevelopment #FrontendDevelopment #LearningJourney Write a JavaScript program that prints numbers from 1 to 5, where each number is printed after a delay equal to its value in seconds. Also, mention the expected output in the comment section.
To view or add a comment, sign in
-
-
PART 3 — Function Hoisting: Declarations vs Expressions 📌 JavaScript Hoisting (Part 3) — Functions Why does this work? sayHi(); function sayHi() { console.log("Hi"); } But this doesn’t? sayHi(); var sayHi = function () { console.log("Hi"); }; Many developers memorize hoisting rules, but still get surprised by function behavior in real code. Here’s what actually happens. During JavaScript’s memory creation phase: • Function declarations The entire function body is stored in memory. That’s why you can call the function before its definition. • Function expressions (using var) Only the variable name is hoisted. Its value is undefined until assignment. Calling it early throws: TypeError: sayHi is not a function. • Arrow functions / let / const They are subject to the Temporal Dead Zone (TDZ). Accessing them before initialization throws a ReferenceError. Key insight: Functions are hoisted only when they are *declared*, not when they are *assigned*. Why this matters: • Prevents subtle runtime crashes • Explains why refactors break “working” code • Helps you reason about execution order instead of guessing Next: What actually happens to hoisting inside block scope and nested functions? #JavaScript #Hoisting #Functions #FrontendInterview #LearningInPublic
To view or add a comment, sign in
-
🤔 Ever seen a ReferenceError even though the variable exists? You just met TDZ. 🧠 JavaScript interview question What is the Temporal Dead Zone (TDZ)? ✅ Short answer • TDZ is the time between entering a scope and initializing a variable • It applies to let, const, and class • Accessing the variable during TDZ throws a ReferenceError 🔍 A bit more detail When JavaScript enters a block ({}): • Memory is allocated for all variables • let / const are hoisted but uninitialized • Until the declaration line runs, the variable is in the Temporal Dead Zone During this time: • The variable exists • But you cannot read or write it 💻 Example { // console.log(x); // ❌ ReferenceError (TDZ) let x = 10; // TDZ ends here console.log(x); // ✅ 10 } { // console.log(y); // ❌ ReferenceError const y = 3; } ⚠️ Sneaky case: default parameters let a = 1; function ok(b = a) { return b; } function error(b = c) { return b; // ❌ ReferenceError when called } let c = 2; 🧩 Common misconceptions • let and const are hoisted (just not initialized) • TDZ is not a special error, it results in ReferenceError • TDZ exists in blocks, functions, and class bodies 💡 Why TDZ exists • Prevents using variables before they’re ready • Eliminates subtle bugs from var • Makes code more predictable and readable 👉 TDZ isn’t an error — it’s JavaScript protecting you. #javascript #webdevelopment #frontend #react #interviewprep #learnjavascript
To view or add a comment, sign in
-
𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀 𝗘𝘃𝗲𝗿𝘆 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 𝗠𝘂𝘀𝘁 𝗞𝗻𝗼𝘄 JavaScript isn’t about memorizing syntax. It’s about understanding how things actually work under the hood. These core concepts decide whether you write working code or production-ready code. 1. Execution Context & Call Stack JavaScript runs code inside execution contexts and manages them using the call stack. This explains why functions execute in order and how stack overflows happen. 2. Hoisting Variables and functions are moved to the top of their scope during compilation. var is hoisted with undefined, while let and const live in the Temporal Dead Zone. 3. Scope & Closures Closures allow functions to remember variables from their parent scope even after execution. This powers data hiding, currying, and many React hooks patterns. 4. this Keyword This is not lexical in JavaScript. Its value depends on how a function is called, not where it’s written. 5. Event Loop & Async JavaScript Promises, async/await, and callbacks, all rely on the event loop, microtask queue, and call stack to handle non-blocking operations. 6. Prototypes & Inheritance JavaScript uses prototype-based inheritance, not classical inheritance. Understanding this clears confusion around classes and __proto__. 7. Shallow vs Deep Copy Objects are copied by reference. Knowing when to deep copy prevents hidden bugs and state mutation issues. 8. Debounce & Throttle Used to control performance in scroll, resize, and input events, critical for real-world apps. Final Thought If you understand these concepts deeply, frameworks become easy. If you skip them, frameworks feel like magic until production breaks. #JavaScript #WebDevelopment #Frontend #JSConcepts #Programming #ReactJS #InterviewPrep #CleanCode
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development