Recently I was preparing for JavaScript and I stumbled upon a simple concept — but most people don’t know the key differences between var and let. Here’s a quick example: ` for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } // Output: 3 3 3 ` ` for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } // Output: 0 1 2 ` Key differences: Scope: var is function-scoped, let is block-scoped. Hoisting & Temporal Dead Zone: var is hoisted and initialized with undefined, let is hoisted but not initialized — accessing it before declaration throws a ReferenceError. Understanding these small details can save you from tricky bugs, especially in loops and async code! #JavaScript #JS #WebDevelopment #FrontendDevelopment #Coding #LearnToCode #DeveloperTips #TechCommunity #CodeSnippet #Programming ## I’d appreciate it if you could share a few more examples to help me understand.
JavaScript var vs let: scope, hoisting, and TDZ
More Relevant Posts
-
JavaScript never fails to surprise. 😅 Check this out 👇 function hello() { console.log("Hello JS!"); } console.log(hello.name); // 👉 "hello" Wait… what?! How does JS know its own name? 🤯 Because every function in JavaScript is actually an object. And objects can have properties. So when you declare a function, JS secretly adds a .name property under the hood 👇 function hello() {} // → hello.name = "hello" Even anonymous ones get an identity if assigned to a variable 👇 const greet = function() {}; console.log(greet.name); // "greet" So yeah — your functions have name tags, even when you forget theirs. 😎 #javascript #frontend #webDevelopment #codingHumor #Coding #programming #developerLife
To view or add a comment, sign in
-
After playing around with map(), filter(), and reduce(), I wanted to go a bit deeper into how JavaScript handles function borrowing and context binding — so I decided to rebuild call(), apply(), and bind() 💪 Here’s how my mini versions turned out 👇 🧠 What I learned: How JavaScript functions can borrow context from other objects Why bind() returns a new function (instead of calling it immediately) How important it is to handle this carefully — one tiny mistake can break everything 😅 Building these gave me a much clearer understanding of how function context and execution work in JS 🔍 #javascript #ReactJs #nodeJs #interview-questions #programming
To view or add a comment, sign in
-
-
Ever felt lost in the complexities of the Node.js EVENT LOOP? 🤔 Let's demystify this core concept for better JavaScript performance! The Node.js Event Loop (powered by V8 and libUV) is the HEARTBEAT ❤️ of asynchronous JavaScript. Understanding it is CRUCIAL for writing efficient Node.js applications. Here are three key takeaways: 💡 Grasp the difference between BLOCKING and NON-BLOCKING I/O. Blocking I/O halts the entire process, non-blocking doesn't. ⏱️ Understand the nuances of `setImmediate` vs. `setTimeout(0)`. While seemingly similar, they behave differently in the event loop's execution order. `setImmediate` prioritizes I/O cycle, while `setTimeout(0)` goes to the timer queue. 🧵 Optimize your UV_THREADPOOL_SIZE. This determines the number of threads available for asynchronous operations. Increasing it can boost performance for CPU-intensive tasks. What's YOUR favorite Node.js performance tip? Share in the comments! 👇 #Nodejs #JavaScript #EventLoop #Asynchronous #Programming #Backend #Performance
To view or add a comment, sign in
-
🚀 JavaScript Gotchas: var vs let in Loops & setTimeout Same code, different output 👇 Ever wondered why this code prints 5 5 5 5 5 instead of 0 1 2 3 4? for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } 💡 Reason: var is function-scoped — only one i exists for the entire loop. setTimeout callbacks run after the loop finishes, so each callback sees the final value of i → 5. ✅ Fix it with let: for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } let is block-scoped — each iteration gets a new copy of i. Now, callbacks “remember” the correct value of i. ✅ Output: 0 1 2 3 4 💡 Key takeaway: var → shared variable in loop → tricky in async callbacks let → separate variable per iteration → safer & predictable ✨ Tip: Even setTimeout(..., 0) behaves the same! The event loop always runs callbacks after the current synchronous code. #JavaScript #CodingTips #FrontendDevelopment #WebDevelopment #Programming #LearnJS #DeveloperTips #AsyncJavaScript #Closures
To view or add a comment, sign in
-
-
Coming from a C++ background, I was used to working with a true multithreaded language, whre multiple functions could wrestle for CPU time. Then I hit JavaScript… and realized it’s single-threaded. Only one function can actually run at a time. which changed how i approach problems. I was working on a small project — basically just making a div move randomly across the screen. Sounds simple, right? But when you give it independent X and Y targets, things get chaotic fast. The movement looks alive, unpredictable, like it’s thinking. That’s when I learned about requestAnimationFrame(). At first, I thought it just “runs things continuously.” Nope. It schedules them — about 60 times a second. You’re not looping; you’re politely asking the browser to let your code run again at the next frame and if you don’t structure it right, like putting requestAnimationFrame() inside your function but not calling it again outside, your function just fires once and quits. Feels small, but understanding this changed how I think about JavaScript, not as a slower , but as a completely different beast that plays by its own rules. #javascript #frontend
To view or add a comment, sign in
-
-
Understanding Debouncing vs Throttling in JavaScript Ever wondered why your scroll or resize events lag? **Debounce**: Waits until the user stops triggering the event. Great for search inputs! **Throttle**: Limits the event to fire at regular intervals—perfect for scroll performance. Here’s a quick debounce example using Lodash: const handleInput = _.debounce(() => { // your logic here }, 300); Tip: Use debounce for search bars, throttle for scroll events. Save your app from laggy nightmares! #JavaScript #WebDevelopment #CodingTips #Frontend #JS #Performance #ToolsOnFire #DevTips #CodeNewbie #100DaysOfCode #LearnToCode #Programming #WebDev #TechTips #foryoupage #foryou🔥
To view or add a comment, sign in
-
-
🔒 JavaScript Closures: The Private Diary Analogy Ever wondered how JavaScript "remembers" things? Let me explain closures with a real-world analogy. Think of a closure like a private diary with a lock: 📖 The diary (outer function) contains your secrets (variables) 🔐 Only you have the key (inner function) to access those secrets ✨ Even after you close the diary, the key still works Why does this matter? The count variable is trapped inside the closure. No one can directly access or modify it from outside. It's like data privacy built into JavaScript! Real-world use case : This powers every search bar you've used that waits for you to stop typing! The key insight: Closures let inner functions remember their environment, even after the outer function has finished executing. Have you used closures in your code today? Share your favorite use case below! 👇 #JavaScript #WebDevelopment #ReactJS #Programming #Frontend #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
🟢 #Mastering #JavaScript #Arrays: #Essential #Methods You Should Know 📝If you work with JavaScript, arrays are your best friend. But knowing the right methods can make your code cleaner, faster, and much more readable. Here are some essentials: #push() – Add elements to the end of an array. #pop() – Remove the last element. #shift() – Remove the first element. #sort() – Arrange elements alphabetically or numerically. #indexOf() – Find the first index of an element, or -1 if it’s missing. #lastIndexOf() – Find the last index of an element. 💡 Knowing these can save your time and help to write more efficient, readable code. 🔔 Follow: Code Harvester for more Updates.🎯 ♻ Repost to help others find it. 💾Save this post for future reference. Document credit goes to the respective owner. #JavaScript #Array #UI #WebDevelopment #CodingTips #Programming #CodeHarvester #Developer #coding #programming #softwaredevelopment
To view or add a comment, sign in
-
💡 Most devs think shallow copies always affect the original… but that’s not true! Let’s clear this common JavaScript misconception 👇 🧩 Example 1 — Primitives let obj = { a: 1, b: 2, c: 3 }; let obj2 = { ...obj }; obj2.b++; console.log(obj.b); // 2 ✅ unchanged ➡️ Here b is a primitive (number). Primitives are copied by value, so obj and obj2 have separate copies. Incrementing obj2.b doesn’t affect obj.b. ⚠️ Example 2 — Nested Objects let obj = { a: 1, b: { x: 10 } }; let obj2 = { ...obj }; obj2.b.x = 99; console.log(obj.b.x); // 99 ❗changed ➡️ Here b is an object, and a shallow copy only copies its reference. Both obj.b and obj2.b point to the same memory. So changing one affects the other. 💬 TL;DR Shallow copy doesn’t always affect the original — it depends on what’s inside the object. Primitives → safe Objects → shared #JavaScript #Frontend #WebDevelopment #ReactJS #CodingTips #Programming #JSFacts
To view or add a comment, sign in
-
💻 JavaScript Code Challenges: Level Up Your Skills 💻 Want to truly master JavaScript? Stop memorizing and start practicing with real engine-level challenges: 1️⃣ Scope & Lexical Environment let a = 10; function test() { let a = 20; console.log(a); } test(); // ? console.log(a); // ? 2️⃣ Closures function counter() { let count = 0; return function() { count++; return count; } } const inc = counter(); console.log(inc()); // ? console.log(inc()); // ? 3️⃣ Hoisting & TDZ console.log(x); // ? let x = 5; console.log(y); // ? var y = 10; ✅ Challenge yourself: Predict the output before running the code. Understand why it behaves that way. That’s how you think like the JS engine! #JavaScript #CodingChallenge #Closures #Scope #Hoisting #LexicalScoping #TDZ #DevCommunity #WebDevelopment #ProgrammingTips #CleanCode
To view or add a comment, sign in
More from this author
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