š¤ Ever wondered⦠Why this works: console.log(a) // undefined var a = 10; But this crashes: console.log(b) // ReferenceError let b = 20; Even though both are declared later? š This is where most developers think they understand JavaScript⦠but they donāt. š Letās break it down: Hoisting & Temporal Dead Zone (TDZ) š§ Hoisting (What actually happens behind the scenes) JavaScript doesnāt execute your code line by line directly. Before execution, it runs a Memory Creation Phase where: ⢠Variables & functions are registered in memory ⢠Declarations are processed first š This is what we call hoisting š¦ Variable Hoisting With var: ⢠Declaration is hoisted ⢠Initialized with undefined So: ⢠You can access it before declaration ⢠But you wonāt get the actual value , since Initialized with undefined in memory creation phase š” Key insight: Hoisting ā moving code Itās about how memory is allocated internally. ā ļø let & const ā Temporal Dead Zone (TDZ) Yes ā let and const are also hoisted. But⦠They stay in a Temporal Dead Zone from: š start of scope ā until declaration line Accessing them early = š„ ReferenceError š” Takeaway: TDZ exists to prevent unpredictable bugs caused by premature access. š Function Hoisting (VIP behavior) Function Declarations are fully hoisted: ā You can call them before declaration But Function Expressions behave differently: ⢠var ā undefined ⢠let/const ā ReferenceError ā” Why this actually matters (not just theory) Understanding hoisting + TDZ helps you: ⢠Avoid silent bugs (undefined issues) ⢠Write predictable, cleaner code ⢠Debug scope-related issues faster ⢠Truly understand how JS engine works š” Final Thought: Most developers memorize hoisting. Good developers understand execution context. Great developers write code that doesnāt depend on hoisting at all. š Iāll be sharing more deep dives like this as I learn & build in public. Follow along if youāre into JavaScript internals š #JavaScript #FrontendDevelopment #WebDevelopment #Hoisting #TDZ #LearnJavaScript #CodingTips #BuildInPublic #100DaysOfCode
JavaScript Hoisting and Temporal Dead Zone Explained
More Relevant Posts
-
Day 2: The Secret Life of a Function Call ā Global vs. Local Execution Context š Today, I went deeper into the "Big Box" of JavaScript to understand exactly what happens when we call a function. Using this simpleĀ squareĀ function as an example, here is the line-by-line magic: š The Two-Phase Performance Phase 1: Memory Allocation Before a single line of code runs, JavaScript scans everything. n,Ā square2, andĀ square4Ā are allocated memory and set toĀ undefined. TheĀ squareĀ function gets its own memory space with theĀ entire function codeĀ stored inside. Phase 2: Code Execution Line 1:Ā nĀ is assigned the valueĀ 2. Line 6:Ā This is where it gets interesting! AĀ Function InvocationĀ happens. š¦ The "Mini Box": Functional Execution Context WhenĀ square(n)Ā is called, aĀ New Execution ContextĀ is created inside the Global one! Memory Phase:Ā A local variableĀ ansĀ is created (undefined). Code Phase:Ā numĀ becomesĀ 2,Ā ansĀ becomesĀ 4. The Return Statement:Ā This is the exit signal. It returns the valueĀ 4Ā toĀ square2Ā andĀ destroysĀ the local execution context immediately. š The Call Stack: The Manager of it All How does JS keep track of these nested boxes? TheĀ Call Stack. It's a stack (LIFO - Last In, First Out). Bottom of stack:Ā Global Execution Context (GEC). When a function is called, it'sĀ pushedĀ onto the stack. When it returns, it'sĀ poppedĀ off. š” Interview Tip:Ā Did you know the Call Stack has many names? Itās also called theĀ Execution Context Stack,Ā Program Stack,Ā Control Stack,Ā Runtime Stack, orĀ Machine Stack. Understanding how the stack grows and shrinks is the key to masteringĀ RecursionĀ and avoiding the dreaded "Stack Overflow"! Drop a "š" if youāre also following the Namaste JavaScript series! #JavaScript #WebDevelopment #CallStack #ExecutionContext #ProgrammingLogic #FrontendEngineer #CodingCommunity #JSFundamentals
To view or add a comment, sign in
-
-
There's always something to gain from going back to the fundamentals. Between client projects and building out systems, I've been carving out time to sharpen my JavaScript. Recently covered: ā Primitive vs Reference Data Types ā Number, Null, Undefined, BigInt, and Symbols ā The typeof operator ā Ternary operators ā Introduction to Object Destructuring None of this is glamorous. But the designers and developers who write clean, predictable code are almost always the ones who took the fundamentals seriously. Still a few more concepts on the list. Sharing the progress as I go. #JavaScript #WebDevelopment #Webflow #LearningInPublic
To view or add a comment, sign in
-
-
hi connections Day 22 of 30: Extending the Prototype with LeetCode 2619 š Todayās challenge, Array Prototype Last, dives into one of JavaScriptās most powerful features: Prototypal Inheritance. Instead of writing a standard function, the task was to enhance the global Array object so that every array can call .last() to retrieve its final element. The Logic By adding a method to Array.prototype, we make it available to every array instance. Inside the function, the this keyword refers to the array itself, allowing us to access its length and indices. Key Takeaways: The "this" Context: Understanding how this refers to the calling object is crucial for building custom utilities. Edge Case Handling: In this problem, returning -1 for empty arrays is a specific requirement that differs from the usual undefined. Efficiency: Accessing an element by index is O(1), making this a lightning-fast operation regardless of array size. Customizing prototypes is a common practice in library development, and mastering it helps in writing cleaner, more intuitive code for complex applications. One more day down, more logic mastered! š»āØ #JavaScript #LeetCode
To view or add a comment, sign in
-
-
šØ JavaScript Brain Teasers That Will Mess With Your Mind. ā console.log(["A"] + ["B"]) š Output: "AB" ā let arr1 = [1,2,3] let arr2 = [4,5,6] console.log(arr1 + arr2) š Output: "1,2,34,5,6" ā console.log(+null) š Output: 0 ā console.log(+"hello") š Output: NaN ā let arr = [1,2,3] let str = "1,2,3" console.log(arr == str) š Output: true ā console.log(10 == [10]) š Output: true ā console.log(10 == [[[[10]]]]) š Output: true ā var fruits = ["orange", "mango", "banana"] var fruitObj = { ...fruits } console.log(fruitObj) š Output: {0: "orange", 1: "mango", 2: "banana"} ā console.log(null ?? true) š Output: true ā console.log(undefined ?? true) š Output: true š„ Takeaway: Most of this comes down to type coercion and how JS internally converts values. #JavaScript #WebDevelopment #Coding #Frontend #Programming #JavaScriptTips #JavaScriptTricks #JSConcepts #LearnJavaScript #FrontendDevelopment #FrontendDeveloper #WebDevCommunity #CodingTips #CodeNewbie #ProgrammingLife #DeveloperCommunity #DevLife #CodeChallenge #DailyCoding #CodeWithMe #TechContent #SoftwareDevelopment #FullStackDeveloper #JSDevelopers #ProgrammingTips #CodeDaily #DevTips
To view or add a comment, sign in
-
Early on, I used var for everything in JavaScript. Then I learned why that's a problem. JavaScript has three ways to declare variables: var ā function-scoped, can be re-declared, and has hoisting quirks that cause subtle bugs. Avoid it in modern code. let ā block-scoped, can be reassigned. Use it when the value needs to change. const ā block-scoped, cannot be reassigned. Use it by default for everything that doesn't change. My rule of thumb: Start with const. If you need to reassign, use let. Never use var. This isn't just style preference ā it's about writing predictable, debuggable code. When I open a file and see const everywhere, I immediately know those values shouldn't change. It's self-documenting. In a team environment, readable and predictable code is just as important as working code. Do you still reach for var out of habit? It's worth breaking.
To view or add a comment, sign in
-
-
JavaScript Under the Hood For the past two weeks, I have been delving into the internal workings of JavaScript. Here are the topics I have covered in detail: * Window object * Memory execution phase * Code execution phase * Global Execution Context * Function Execution Context * Closures and lexical scopes * Binding the 'this' keyword * Reference types * Heap and stack * DOM: * Repaint * Reflow * C++ DOM nodes * Event capturing and bubbling * Render tree Asynchronous JavaScript: * Event loop * Call stack * Promises * Microtasks * Macrotasks * Callback hell Objects: * Prototypes * The 'this' keyword * Shallow copy * Deep copy And many more topics. you can watch Lydia Hallie Youtube channel to learn some of the concepts . youtube channel ** https://lnkd.in/dFPqHBUv
To view or add a comment, sign in
-
-
Day 01: Precision Matters š¢ Kicking off my coding journey by tackling a classic:Ā The Plus Minus Challenge. The Problem: Given an array of integers, calculate the ratios of positive numbers, negative numbers, and zeros. The catch? The output must be precise to six decimal places. The Solution: Itās all about iteration and formatting. By looping through the array and categorizing each element, we can determine the counts. The key to meeting the precision requirement in JavaScript is using theĀ .toFixed(6)Ā method. javascript function plusMinus(arr) { let n = arr.length; let positive = 0, negative = 0, zero = 0; for(let val of arr) { if(val > 0) positive++; else if(val < 0) negative++; else zero++; } console.log((positive/n).toFixed(6)); console.log((negative/n).toFixed(6)); console.log((zero/n).toFixed(6)); } plusMinus(arr); Key Takeaway: Even simple logic requires attention to detailāespecially when it comes to floating-point precision! #CodingChallenge #JavaScript #ProblemSolving #100DaysOfCode #DataStructures
To view or add a comment, sign in
-
š Dynamic Currying in JavaScript ā Why it actually matters At first, currying feels like a trick: sum(1)(2)(3) But the real power isnāt syntax ā itās reusability. š” The idea š Fix some arguments now š Reuse the function later š§ Example const filter = fn => arr => arr.filter(fn); const filterEven = filter(x => x % 2 === 0); filterEven([1,2,3,4]); // [2,4] Instead of repeating logic everywhere, you create reusable building blocks. ā” Real-world uses API helpers ā request(baseUrl)(endpoint) Logging ā logger("ERROR")(msg) Event handlers ā handleClick(id)(event) Validation ā minLength(8)(value) š§ Key takeaway Currying isnāt about fancy functions. Itās about writing code that is: ā Reusable ā Composable ā Cleaner Libraries like Lodash and Ramda use this pattern heavily. Once this clicks, your approach to writing functions changes completely. #JavaScript #WebDevelopment #FunctionalProgramming #Currying #CleanCode #Frontend #Coding #100DaysOfCode #DeveloperJourney #TechCommunity
To view or add a comment, sign in
-
-
š Understanding Factory Functions in JavaScript Ever felt confused using constructors and the new keyword? š¤ Thatās where Factory Functions make life easier! š A Factory Function is simply a function that creates and returns objects. š” Why use Factory Functions? āļø No need for new keyword āļø Easy to understand (perfect for beginners) āļø Avoids this confusion āļø Helps in writing clean and reusable code āļø Supports data hiding using closures š§ Example: function createUser(name, age) { return { name, age, greet() { console.log("Hello " + name); } }; } const user = createUser("Sushant", 21); user.greet(); ā ļø One downside: Methods are not shared (can use more memory) šÆ Conclusion: Factory Functions are a great way to start writing clean and maintainable JavaScript code without complexity. #JavaScript #WebDevelopment #FrontendDeveloper #CodingJourney #LearnToCode #100DaysOfCode
To view or add a comment, sign in
-
-
š I finally understood Closures in JavaScript (and it was confusing at first) At first, I thought every function call resets variables⦠But closures completely changed my understanding. Hereās the simple idea š š A closure is when a function remembers variables from its outer function, even after the outer function has finished. Example: function outer() { let count = 0; return function () { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 š” Why does this work? Because the inner function āremembersā the variable count. Even though outer() has already executed, the value is not lost. š„ Key takeaway: Normal functions ā reset values every time Closures ā keep values alive This concept is widely used in: āļø Counters āļø Data hiding āļø Event handlers Still practicing and improving my JavaScript fundamentals š» Have you ever struggled with closures? š¤ #JavaScript #WebDevelopment #MERNStack #Coding #Learning #100DaysOfCode
To view or add a comment, sign in
-
Explore related topics
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