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
JavaScript Hoisting Explained
More Relevant Posts
-
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
-
One line of JavaScript can replace an entire if/else block. The ternary operator might be the “question” that your code needs. The formally named “Conditional (ternary) operator” goes by many common names including: a ternary, one-line conditional, and shorthand if/else. It’s a powerful bit of JavaScript that can help you cut down on some of your if statements. A ternary’s syntax is structured sort of like a question: condition ? valueIfTruthy : valueIfFalsy The condition is an expression whose value will come in as either truthy or falsy - no those aren’t typos. Truthy and falsy are values that when considered in a boolean context come back as true or false, respectively. All values are truthy except for: false, 0, -0, 0n, null, undefined, NaN, and document.all. Let’s take this syntax and apply it to a practice example, checking if the user is a Prime member. const isPrimeMember = true; const shippingTime = isPrimeMember ? "2 Days" : "7 Days"; // shippingTime = 2 Days If we didn’t use a ternary, our code might look something like this: const isPrimeMember = true; if (isPrimeMember) { shippingTime = "2 Days"; } else { shippingTime = "7 Days"; } This code is totally valid, but you can see that by using a ternary we’ve used 2 lines rather than 7. Once you get comfortable with ternaries, you’ll start spotting places where they make your code cleaner and easier to read. They show up everywhere - especially in React - so getting familiar with them early pays off fast.
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
-
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟴 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
-
-
🤔 Quick question: When JavaScript runs async code, where does everything actually go? After learning about the Call Stack and Event Loop, I realized something important: JavaScript doesn’t work alone — it collaborates with Web APIs and queues 👇 --------------------------- console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); ---------------------------- Output: - Start - End - Timeout 💡 What happens behind the scenes? - console.log("Start") → pushed to the Call Stack - setTimeout → handed off to Web APIs - console.log("End") → runs immediately Once the Call Stack is empty: - Event Loop checks the Task Queue - setTimeout callback is pushed back to the stack - Callback executes How the pieces fit together Call Stack → executes JavaScript Web APIs → handle timers, DOM events, network calls Queues → hold callbacks waiting to run Event Loop → coordinates everything Takeaway JavaScript executes code using the Call Stack, offloads async work to Web APIs, and uses the Event Loop to decide when callbacks can run. #JavaScript #WebDevelopment #FullStack #LearningInPublic
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
-
So, you're trying to wrap your head around this weird thing in JavaScript. It's like, you write a function inside an object, and it's all good - it knows who it is. But then you pass it to another function, and suddenly it's like, "Wait, who am I again?" It's because "this" in JavaScript isn't a fixed label, it's more like a question. When the code runs, the function looks around and asks, "Who called me?" - and the answer is pretty simple, really. Just look to the left of the dot. If you see an object, that's who "this" is. No object? Thenthis is undefined. Here's the thing: if you call a function through an object, "this" is that object - makes sense, right? But if you call a function without an object,this is undefined. And then there are these two methods, .call() and .bind(), that can kind of forcethis to be a specific object. Use .call(), and it's like you're telling the function, "For this one time, you're this object" - it's a temporary thing. But use .bind(), and you're creating a new function that remembers its owner forever - it's like giving it a permanent identity. It's all about context, really. In JavaScript, your identity isn't about who you are, it's about who's holding you at the moment you speak - it's a pretty fluid thing. Check out this article for more on the secret life of JavaScript: https://lnkd.in/grANWBg6 #JavaScript #Identity #Coding
To view or add a comment, sign in
-
Why does 0 == false return true in JavaScript? 😵 If this confuses you, you're not alone. I wrote a guide explaining == vs === and how to avoid common pitfalls that trip up even experienced developers. Link below 👇 https://lnkd.in/dGP2aJZr #JavaScript #CodingTips #WebDev
To view or add a comment, sign in
-
Understanding why Promise.all() needs an array in JavaScript Many developers try this and get confused 👇 ❌ Wrong way Promise.all(p1, p2); ✅ Correct way Promise.all([p1, p2]); 🤔 Why does this happen? Promise.all() accepts only ONE argument, and that argument must be an iterable (most commonly an array). 👉 An array allows JavaScript to loop through multiple promises and wait for all of them to resolve. ✅ Working example let p1 = new Promise((resolve) => { resolve(1); }); let p2 = new Promise((resolve) => { resolve(2); }); Promise.all([p1, p2]) .then((data) => { console.log(data); // [1, 2] }); ❌ Why `Promise.all(p1, p2)` throws an error? When you write: Promise.all(p1, p2); JavaScript treats it as: Promise.all(p1); But p1 is a "Promise object", not an iterable like an array. So JS throws: TypeError: object is not iterable 🧠 Easy way to remember > Promise.all waits for a collection of promises, not individual ones Always wrap promises inside an array. ⚠️ One more important thing If any promise rejects, Promise.all() immediately rejects. Promise.all([Promise.resolve(1), Promise.reject("Error")]) .catch(console.error); // Error 💡 Hope this helps someone avoid a common JavaScript pitfall! . . . . . #SRYTAL #JavaScript #Promises #WebDevelopment #Frontend #Learning #Promise.all #Growtogether
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