So, JavaScript has three ways to declare variables - and it's kinda weird. It's all about how var, let, and const work with JavaScript's execution model. Think of it like a big machine: when you declare a variable, JavaScript creates this thing called a Lexical Environment, which is like a container that stores variables and functions. It's got two main parts: an Environment Record and an outer reference to the parent environment. Simple. But here's where things get interesting - var, let, and const all interact with these structures in different ways. Var creates bindings in Function Environment Records, and they're initialized to undefined right away, which is pretty old-school. Let, on the other hand, creates bindings in Block Environment Records, and it's got this temporary dead zone (TDZ) thing going on, which can be a bit tricky to wrap your head around. And then there's const, which is like let, but its bindings are marked immutable - so, you can't change 'em once they're set. Understanding how all this works is key to predicting behavior and debugging issues in your code. It's like being a detective - when you see weird scoping bugs, you can trace through the environment creation and figure out exactly where a variable lives. And, honestly, it's pretty cool once you get the hang of it. So, if you want to learn more, check out this article: https://lnkd.in/g72BVQUZ #JavaScript #Variables #CodingStrategy
JavaScript Var Let Const: Understanding Lexical Environments
More Relevant Posts
-
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 does JavaScript even have closures? Why not just write simple functions instead of this complex syntax? At first glance, this question may seem dismissive, but it actually delves into a profound topic. A "simple function" typically: - Executes - Returns a value - Loses all local state once it finishes This model works for pure, short-lived logic. However, most JavaScript code is not short-lived. The real problem closures solve is that modern JavaScript requires functions that: - Run later (callbacks, events) - Run repeatedly - Run asynchronously - Still remember what happened before Without closures, a function would forget everything once it exits. Closures allow a function to: - Capture variables from its outer scope - Maintain access to them even after the outer function has returned This is not merely about syntax; it’s about preserving state over time. The idea of “just use globals” is problematic. Without closures, we would have to: - Store state in global variables - Pass state manually everywhere - Rely heavily on classes for simple problems These approaches lead to: - Tight coupling - Hard-to-debug bugs - Code that doesn’t scale Closures provide a clean and safe solution to these issues. Real features built on closures include: - Event listeners - setTimeout / async callbacks - Debounce & throttle - Function factories - State management patterns in frameworks Closures are not optional; they are foundational. The key takeaway is that closures exist because JavaScript needs a way to keep state without resorting to globals or classes. Once this concept is grasped, closures become less about complexity and more about necessity. #JavaScript #Closures #FrontendInterviews #SoftwareEngineering #WebDevelopment #JSConcepts
To view or add a comment, sign in
-
JavaScript's got a thing or two to teach us about variables. It's pretty straightforward, actually - everything's passed by value. But, what's that even mean? It means when you pass a primitive, like a number or a string, JavaScript just makes a copy of it. Simple as that. The original and the copy, they're like two separate entities, living their best lives independently. So, yeah: Primitives are stored right in the variable, no fuss. But objects, on the other hand, are a different story - they're passed by value too, but the value is actually a reference to where the object lives in memory. Think of it like sending someone a map to your house, instead of the actual house. You can make copies of objects, though, using the spread operator or structuredClone() - it's like taking a snapshot of the object, so you can play around with the copy without messing up the original. Here's the lowdown: Primitives are safe, they won't get changed on you. Objects and arrays, though, they share references, so be careful not to mess things up. Just use spread or structuredClone() to make copies, and you're golden. And, honestly, embracing immutability is the way to go - it makes your code predictable, and performant, like a well-oiled machine. Check it out: https://lnkd.in/g-Nj9Rh6 #JavaScript #Variables #Immutability
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
-
Ever wondered what actually happens behind the scenes when JavaScript runs your code? 🤔 How Variables & Functions Work Behind the Scenes in JavaScript Today I focused on understanding what actually happens inside the JavaScript engine when we write variables and functions — and it completely changed how I read JS code. 🧠 Step 1: JavaScript Creates an Execution Context Before executing any code, JavaScript creates an Execution Context. This happens in two phases: 1. Creation Phase (Memory Allocation Phase) In this phase, JavaScript scans the entire code before running it and prepares memory. ✔ Variables var variables are allocated memory and initialized with undefined let and const are also allocated memory, but they stay in the Temporal Dead Zone (TDZ) until initialized ✔ Functions Function declarations are stored fully in memory (function body included) Function expressions & arrow functions behave like variables and depend on var / let / const 👉 This is the real reason hoisting exists. 2.Execution Phase (Code Runs Line by Line) Now JavaScript starts executing the code: Variables get their actual values Functions are executed when they are called A new Function Execution Context is created for every function call Each context is pushed to the Call Stack After execution, it is removed from the stack Why Functions Can Be Called Before Declaration? because function declarations are fully hoisted during the creation phase. 💡 Key Takeaways JavaScript doesn’t execute code directly — it prepares first Hoisting is a byproduct of the creation phase var, let, and const differ because of how memory is allocated Understanding execution context makes debugging much easier. Mastering the basics is what truly levels up a developer. Thanks to Anshu Pandey and Sheryians Coding School #JavaScript #JavaScriptbasics #ES6 #JSEngine #coding
To view or add a comment, sign in
-
-
🚀 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
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟴 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
-
-
Many people use JavaScript every day. Very few truly understand how JavaScript executes code. In JS Mastery #4, I’ve covered one of the most misunderstood yet core concepts in JavaScript — Hoisting. But this is not just about memorizing rules like “var is hoisted, let and const are not”. 👉 Watch the video here: https://lnkd.in/gkiWnXKE This video goes deeper 👇 🔹 How the JavaScript Engine actually runs your code 🔹 What an Execution Context is (memory phase vs execution phase) 🔹 How the Call Stack manages execution 🔹 Why let and const behave differently 🔹 What Temporal Dead Zone (TDZ) really means 🔹 Why certain errors happen before your code even runs All examples are shown with variables only (var, let, const) so that the fundamentals are crystal clear before moving to functions. If JavaScript has ever felt “weird” or “magical” to you — this video is meant to remove that confusion and replace it with logic and clarity. This is part of my JS Mastery series, where the goal is simple: build strong fundamentals before touching frameworks. Feedback and discussions are always welcome 👇 Let’s learn JavaScript the right way. #JavaScript #JSMastery #WebDevelopment #ProgrammingFundamentals #LearnJavaScript #Hoisting #ExecutionContext #CallStack #TDZ #Hosiyar
To view or add a comment, sign in
-
-
JavaScript usually feels fine until the same function suddenly behaves differently, and nothing makes sense. 👀 The code looks identical, nothing was touched, and yet the result changed. Frustration usually shows up right there. Not because of broken logic, but because 'this' isn't what it looked like. 🎭 And that's the tricky part. It's not a syntax problem; it's about execution context. In JavaScript, 'this' isn't locked in when the function is written. Its value is determined when the function runs. Change how it's called, and the behavior shifts with it. Same code, different call. Once that clicks, those "why is this undefined?" moments stop feeling random. They start feeling predictable. 🧠 The confusion fades because there's finally a mental model behind it. So here's the question worth pausing on: When exactly does JavaScript decide what 'this' points to? This is where it starts to feel obvious: https://lnkd.in/dWpngz9z
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