Day 3: JavaScript Hoisting — Magic or Logic? Yesterday, we learned that JavaScript creates memory for variables before it executes the code. Today, let’s see the most famous (and sometimes confusing) result of that: Hoisting. What is Hoisting? Hoisting is a behavior where you can access variables and functions even before they are initialized in your code without getting an error. Wait... why didn't it crash? 🤔 If you try this in other languages, it might throw an error. But in JS: During Memory Phase: JS saw var x and gave it the value undefined. It saw the function getName and stored its entire code. During Execution Phase: When it hits console.log(x), it looks at memory and finds undefined. When it hits getName(), it finds the function and runs it! ⚠️ The "Let & Const" Trap Does hoisting work for let and const? Yes, but with a catch! They are hoisted, but they are kept in a "Temporal Dead Zone". If you try to access them before the line where they are defined, JS will throw a ReferenceError. Pro Tip: Always define your variables at the top of your scope to avoid "Hoisting bugs," even though JS "magically" handles them for you. Crucial Takeaway: Hoisting isn't code physically moving to the top; it’s just the JS Engine reading your "ingredients" before "cooking" (Phase 1 vs Phase 2). Did you know about the Temporal Dead Zone? Let me know in the comments! #JavaScript #WebDev #100DaysOfCode #Hoisting #CodingTips #FrontendDeveloper
Understanding JavaScript Hoisting and the Temporal Dead Zone
More Relevant Posts
-
🚀 Just published: The JavaScript Variable Declaration Trilogy After years of writing JavaScript, I decided to go beyond the usual "use const by default" advice and explore the why behind var, let, and const. In this deep dive, I cover: ✅ The Temporal Dead Zone (and why it catches bugs you didn't know you had) ✅ The closure gotcha that's bitten every JS developer at least once ✅ Why const doesn't mean immutable (and what it actually protects) ✅ Performance implications nobody talks about ✅ Real-world horror stories and how let/const solve them This isn't another surface-level comparison it's about building the right mental models to write bulletproof JavaScript. Full breakdown with visual walkthroughs 👇 https://lnkd.in/ehQs6Nbf #JavaScript #WebDevelopment #Programming #ES6 #SoftwareEngineering #CodingTips #FrontendDevelopment
To view or add a comment, sign in
-
So JavaScript has this thing called hoisting. It's like a behind-the-scenes magic trick. Variables and functions get moved to the top of their scope. This happens way before the code actually runs, during the memory creation phase. Only the declarations get hoisted, not the actual values. Think of it like setting up a stage - you're just putting the props in place, but not actually using them yet. JavaScript runs in two phases: memory creation and code execution. During the memory creation phase, variables declared with var are like empty boxes - they're initialized with undefined. Function declarations, on the other hand, are like fully formed actors - they're stored in memory, ready to go. This means you can access variables before you've even assigned a value to them. It's like trying to open an empty box - you'll just get undefined. But if you try to access a variable that doesn't exist at all, JavaScript will throw a ReferenceError - it's like trying to open a box that's not even there. Here's the thing: function declarations are fully hoisted, so you can call them before they're even declared. But function expressions are like variables - they're hoisted as undefined, so trying to call them as a function will throw a TypeError. For example, consider this code: var x = 7; function getName() {...}. You can call getName() before it's declared, and it'll work just fine. But if you try to access x before it's assigned a value, you'll just get undefined. It's all about understanding how hoisting works in JavaScript. Check out this article for more info: https://lnkd.in/g_Jh4Vd8 #JavaScript #Hoisting #Coding
To view or add a comment, sign in
-
✅ Why JavaScript Sorted These Numbers WRONG (But Correctly 😄) This morning’s code was: const nums = [1, 10, 2, 21]; nums.sort(); console.log(nums); 💡 Correct Output [1, 10, 2, 21] Yes — not numerically sorted 👀 Let’s understand why. 🧠 Deep but Simple Explanation 🔹 How sort() works by default 👉 JavaScript converts elements to strings first 👉 Then sorts them lexicographically (dictionary order) So the numbers become strings internally: ["1", "10", "2", "21"] Now JS sorts them like words: "1" "10" "2" "21" Which gives: [1, 10, 2, 21] 🔹 Why this is dangerous Developers expect numeric sorting: [1, 2, 10, 21] But JavaScript does string comparison by default. That’s why this bug appears in: scores prices rankings pagination 🔹 Correct way to sort numbers nums.sort((a, b) => a - b); Now JavaScript compares numbers, not strings. 🎯 Key Takeaways : sort() mutates the original array Default sort() = string comparison Numbers must use a compare function This is one of the most common JS bugs 📌 If you remember only one thing: Never trust sort() without a comparator. 💬 Your Turn Did this ever break your code? 😄 Comment “Yes 😅” or “Learned today 🤯” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
So, you wanna get a grip on JavaScript. It's all about functions and objects, really. They're the building blocks. A function is like a recipe - it's a set of instructions that does something, and you can use it over and over. You can make functions in a few different ways: - the classic function declaration, - function expressions, which are kinda like assigning a function to a variable, - and then there's the arrow function, which is like a shorthand way of doing things. For example, you can use functions like this: console.log(greet("Ajmal")); - it's like calling a friend to say hello. Or, you can create a function that adds two numbers together, like this: const add = function (a, b) { return a + b; }; - it's basic, but it works. And then there's the arrow function, which is super concise, like this: const multiply = (a, b) => a * b; - it's like a quick math trick. Objects, on the other hand, are like containers - they store data in key-value pairs, so you can keep things organized. It's like having a toolbox, where you can store all your functions and data in one place. You can use objects to make your code more manageable, and that's a beautiful thing. Check out this article for more info: https://lnkd.in/gTMkkSGP #JavaScript #Functions #Objects
To view or add a comment, sign in
-
🔍 Null vs Undefined in JavaScript -> Understanding the difference between null and undefined and Let's break down. 🔹 undefined undefined means a variable has been declared but not assigned any value. It is the default value assigned by the JavaScript engine. Common cases where you get undefined: A variable declared but not initialized A function that does not return anything Accessing a non-existent object property Examples: let a; console.log(a); // undefined function test() {} console.log(test()); // undefined let obj = {}; console.log(obj.name); // undefined ✔ undefined is a falsy value ✔ Assigned automatically by JavaScript 🔹 null null is an intentional assignment that represents no value or an empty object reference. It is explicitly set by the developer. Example: let user = null; console.log(user); // null ✔ null is also a falsy value ✔ It must be assigned manually 🔹 Behavior in Arithmetic Operations JavaScript handles null and undefined differently in calculations: null + 20 // 20 → null is converted to 0 undefined + 20 // NaN 🔹 Equality Comparison null == undefined // true (loose equality) null === undefined // false (strict equality) 🧠 Key Takeaway Use undefined when a value is not yet assigned (default behavior) Use null when you want to explicitly indicate “no value” Ajay Suneja 🇮🇳 ( Technical Suneja ) #JavaScript #WebDevelopment #Frontend #Programming #JSBasics
To view or add a comment, sign in
-
JavaScript Hoisting: The Concept That Separates “I use JS” from “I understand JS” Hoisting is one of those JavaScript behaviors that silently explains why some code works, and why some bugs are so hard to catch. In JavaScript, code runs in two phases: 1️⃣ Compilation (creation) phase 2️⃣ Execution phase During compilation, JavaScript sets up memory for variables and functions. This is where hoisting happens. 🔹 var hoisting Only the declaration is hoisted, not the initialization. ex: console.log(x); // undefined var x = 5; Behind the scenes, JavaScript treats it like: var x; console.log(x); x = 5; No error, but also no value yet. This behavior has caused countless subtle bugs in real-world apps. 🔹 Function declarations Function declarations are fully hoisted, name and body. sayHello(); // works function sayHello() { console.log("Hello"); } This is why function declarations behave differently from function expressions. 🔹 let & const (ES6) They are hoisted, but not initialized. Accessing them before declaration throws a ReferenceError. console.log(y); // ReferenceError let y = 10; This period is known as the Temporal Dead Zone (TDZ), a design choice to make code safer and more predictable. 💡 Why this matters in real projects - Explains unexpected undefined - Helps debug scope-related issues - Shows you understand how JS actually works under the hood 📌 Best practice Don’t rely on hoisting. Write code that’s clear, intentional, and predictable, your future self (and your team) will thank you. #JavaScript #Frontend #WebDevelopment #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
𝗛𝗼𝘄 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗪𝗼𝗿𝗸𝘀 𝗜𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝗹𝘆 You want to know how hoisting works in JavaScript. Hoisting is when JavaScript moves declarations to the top of their scope. This happens during the memory creation phase, before code execution. JavaScript runs in two phases: - Memory Creation Phase: JavaScript parses the code and allocates memory for variable and function declarations. - Execution Phase: Code runs line by line, and assignments happen. There are different types of hoisting in JavaScript: - var hoisting: fully hoisted - let and const hoisting: hoisted but not initialized - function declaration hoisting: fully hoisted - function expression hoisting: not fully hoisted For example, with var hoisting: ``` console.log(a); var a = 10; ``` Internally, it becomes: ``` var a; console.log(a); a = 10; ``` But with let and const hoisting, you get a ReferenceError if you try to access the variable before declaration. When JavaScript runs your code, it creates an execution context. This context has two main things: memory and code. Memory stores variables and functions, and code executes line by line. Source: https://lnkd.in/d9Zen2Dc
To view or add a comment, sign in
-
Day 179: Peeling Back the JavaScript Layers 🧅 Today was all about moving beyond "how to code" and diving into how JavaScript actually works under the hood. I spent the day dissecting objects, the prototype chain, and the evolution of asynchronous patterns. 🧬 The Prototype Power I finally stopped looking at __proto__ as a mystery and started seeing it as a roadmap. Understanding how objects inherit properties from their parents—and how we can extend built-in objects with custom methods like getTrueLength()—is a total game-changer for writing dry, efficient code. ⏳ The Async Evolution: Escaping "Hell" We’ve all seen it: the pyramid of doom known as Callback Hell. Today, I practiced refactoring those nested messes into clean Promises and eventually into the sleek, readable Async/Await syntax. It's not just about making the code work; it's about making it readable for the "future me." 👯 Shallow vs. Deep Copy One of the most important lessons today was realizing that the Spread Operator (...) isn't a magic wand for copying. Shallow Copy: Quick and easy, but nested objects are still linked to the original. Deep Copy: Using JSON.parse(JSON.stringify()) to completely sever ties and create a truly independent clone. Key takeaways: Object Mastery: Using Object.values() and hasOwnProperty to navigate data safely. Array Essentials: Re-mastering map, reduce, and Array.from(). The 'New' Keyword: Understanding how it establishes that hidden link to the constructor's prototype. If you’re not understanding the prototype chain, you’re only using 50% of JavaScript’s power! #100DaysOfCode #JavaScript #WebDevelopment #CodingJourney #SoftwareEngineering #AsyncJS #Prototypes #BuildInPublic
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