🧠 JavaScript Question: Why does this become undefined in strict mode? While revisiting some JavaScript fundamentals, I came across an interesting behavior related to default this binding. Consider this code: "use strict"; function showUser() { console.log(this); } showUser(); Output: undefined But remove "use strict" and run it again: function showUser() { console.log(this); } showUser(); Output: window So why does this happen? ⚙️ The Reason In JavaScript, the value of this depends on how a function is called, not where it is defined. If a function is called without an object, JavaScript applies default binding. But historically this created a serious problem. 📜 The ES3 Problem Before ECMAScript 5, calling a constructor without new would silently modify the global object. function User(name) { this.name = name; } User("John"); // forgot 'new' console.log(window.name); Output: John This accidentally polluted the global object, which could break applications. 🚨 The ES5 Fix — Strict Mode To prevent this, strict mode changed the default behaviour. Default binding now becomes: Non-strict mode → this = window Strict mode → this = undefined Now if we forget new, JavaScript throws an error instead of silently modifying globals. ✅ Takeaway Strict mode was introduced to make JavaScript safer and less error-prone, especially for mistakes like calling constructors without new. Understanding these small design decisions helps us appreciate how JavaScript evolved from ES3 to modern standards. #javascript #frontenddevelopment #webdevelopment #softwareengineering #ecmascript
JavaScript this binding in strict mode
More Relevant Posts
-
You write a variable… but JavaScript says it doesn’t exist. How? When JavaScript enters a new scope, it scans for all variable declarations before running any code. Variables declared with let and const are acknowledged, but intentionally kept off-limits until their declaration line is reached. In JavaScript, variables declared with let and const are hoisted, but they cannot be used before their declaration line runs. The period between the start of the scope and the actual declaration is called the Temporal Dead Zone (TDZ). During this time: The variable technically exists in memory But JavaScript blocks any access to it Example: console.log(user); -> ReferenceError let user = "Daniel"; Even though user is hoisted, accessing it before the declaration throws an error because it’s still inside the TDZ(Temporal Dead zone). var had no TDZ - and that freedom quietly caused bugs that were notoriously hard to trace. let and const were introduced with TDZ deliberately, to enforce order, intention, and predictability in your code. With let and const, timing matters. The simple rule that keeps you safe: Always declare your variables before you use them. Every time. No exceptions. The TDZ was designed to prevent unpredictable bugs and force cleaner, more intentional code. It’s one of the subtle ways modern JavaScript improves reliability.
To view or add a comment, sign in
-
🧠 Day 6 — Closures in JavaScript (Explained Simply) Closures are one of the most powerful (and frequently asked) concepts in JavaScript — and once you understand them, a lot of things start to click 🔥 --- 🔐 What is a Closure? 👉 A closure is when a function “remembers” variables from its outer scope even after that scope has finished executing. --- 🔍 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 --- 🧠 What’s happening? inner() still has access to count Even after outer() has finished execution This happens because of lexical scoping --- 🚀 Why Closures Matter ✔ Data privacy (like encapsulation) ✔ Used in callbacks & async code ✔ Foundation of React hooks (useState) ✔ Helps create reusable logic --- ⚠️ Common Pitfall for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 👉 Output: 3 3 3 ✔ Fix: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } --- 💡 One-line takeaway: 👉 “A closure remembers its outer scope even after it’s gone.” --- If you’re learning JavaScript fundamentals, closures are a must-know — they show up everywhere. #JavaScript #Closures #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🔥 Regular Function vs Arrow Function in JavaScript — what's the real difference? This confused me when I started. Here's everything you need to know 👇 ━━━━━━━━━━━━━━━━━━━━━━━━━━ 1. The syntax is different Regular functions use the function keyword. Arrow functions use a shorter ( ) => syntax — less typing, cleaner code. 2. The "this" keyword behaves differently This is the BIG one. 📌 Regular function → has its own this. It changes depending on HOW the function is called. 📌 Arrow function → does NOT have its own this. It borrows this from the surrounding code. That's why arrow functions are great inside classes and callbacks — they don't lose track of this. 3. Arrow functions can't be used as constructors You can do new regularFunction() — works fine. You can NOT do new arrowFunction() — it throws an error. 4. Arguments object Regular functions have a built-in arguments object to access all passed values. Arrow functions don't — use rest parameters (...args) instead. ━━━━━━━━━━━━━━━━━━━━━━━━━━ ✅ When to use which? → Use arrow functions for short callbacks, array methods (.map, .filter), and when you need to keep this from the outer scope. → Use regular functions when you need your own this, use as a constructor, or need the arguments object. Understanding this = leveling up as a JavaScript developer 🚀 #JavaScript #WebDevelopment #100DaysOfCode #Frontend #CodingTips #Programming
To view or add a comment, sign in
-
If JavaScript is single‑threaded, how does it still handle Promises, API calls, and Timers without blocking the application? The answer lies in the Event Loop. Let’s take a simple example: What would be the output of the below code? console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Some may guess the output to be: Start End Timeout Promise But the actual output is: Start End Promise Timeout So what is happening behind the scenes? 🔵 Synchronous Code Being synchronous, console.log("Start") and console.log("End") run immediately in the Call Stack. 🔵 Promises Resolved promises go to the Microtask Queue which is executed next. 🔵 setTimeout Timer callbacks go to the Macrotask Queue, even if the delay is '0ms', which is executed last. ✅ Simple flow to remember Synchronous Code → Promises (Microtasks) → setTimeout (Macrotasks) So even with 0 delay, Promises will always execute before setTimeout. Understanding this small but important detail will help developers debug async behavior and write more predictable JavaScript applications. #javascript #webdevelopment #eventloop #asyncprogramming
To view or add a comment, sign in
-
One of the first things that trips up JavaScript developers — at every level — is the `this` keyword. It doesn't work like most other languages. In JavaScript, `this` is not about where a function is written. It's about how it is called. Once you understand the 4 binding rules, it becomes very predictable. 01 — Default binding When called alone, `this` is the global object (or `undefined` in strict mode) 02 — Implicit binding When called on an object, `this` is that object 03 — Explicit binding `.call()`, `.apply()`, and `.bind()` let you set `this` manually 04 — Arrow functions They don't have their own `this`. They inherit it from the surrounding scope // Rule 2 — implicit const user = { name: "Aman", greet() { console.log(this.name); } }; user.greet(); // "Aman" — this = user // Rule 3 — explicit greet.call({ name: "Aman" }); // "Aman" — this = the object you passed // Rule 4 — arrow function inside a method const timer = { start() { setTimeout(() => console.log(this), 1000); // this = timer ✓ } }; The most practical takeaway from Rule 4: 🔵 Regular function → `this` is set by the caller 🟢 Arrow function → `this` is set by the enclosing scope This is why arrow functions are so useful inside callbacks and event handlers — they hold onto the `this` you actually want, without any extra work. Which rule do you find most developers struggle with? I'd love to hear your experience in the comments. 👇 #JavaScript #WebDevelopment #SoftwareEngineering #Programming #100DaysOfCode
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽: 𝗦𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗮𝗻𝗱 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗖𝗼𝗱𝗲 You want to understand how JavaScript works. Let's look at an example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What do you think the output will be? - Start - End - Promise - Timeout This happens because JavaScript runs code in a specific order. - Synchronous code runs line by line. - Asynchronous code runs in the background. JavaScript uses something called the Event Loop to manage tasks. - The Event Loop checks for tasks to run. - It uses two queues: microtasks and macrotasks. - Microtasks are small, important tasks like Promises. - Macrotasks are normal asynchronous tasks like setTimeout. When you run the code, here's what happens: 1. JavaScript runs the synchronous code: Start 2. It schedules the setTimeout task. 3. It runs the final synchronous line: End 4. The Event Loop checks the microtask queue and runs the Promise callback: Promise 5. Finally, it checks the macrotask queue and runs the setTimeout callback: Timeout Understanding the Event Loop helps you work with: - API requests - Asynchronous tasks Try to predict the output of this code: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); Use the rule we learned: - Synchronous code - Microtasks (Promises) - Macrotasks (Timers, setTimeout) Write your answer in the comments. Source: https://lnkd.in/gbAJefcw
To view or add a comment, sign in
-
🚀 Understanding "var" Scope in JavaScript In JavaScript, there are mainly three types of scope: 1️⃣ Global Scope – Variables declared outside any function are accessible everywhere in the program. 2️⃣ Function Scope – Variables declared inside a function can only be used inside that function. 3️⃣ Block Scope – Variables declared inside blocks like "{ }" (for example in "if", "for", etc.) are only accessible inside that block. However, the important thing to remember is: 👉 The "var" keyword only follows Global Scope and Function Scope. ❌ It does NOT follow Block Scope. Let’s look at a simple example: if (true) { var message = "Hello World"; } console.log(message); // Output: Hello World Even though "message" is declared inside the "if" block, we can still access it outside the block. This happens because "var" ignores block scope. Now look at a function example: function test() { var number = 10; console.log(number); // 10 } console.log(number); // Error: number is not defined Here, "number" is declared inside the function, so it cannot be accessed outside the function. ✅ Key Takeaway: - "var" → Global Scope + Function Scope - "var" ❌ does not support Block Scope That’s why modern JavaScript developers prefer "let" and "const", because they properly support block scope. #JavaScript #WebDevelopment #Programming #BackendDevelopment
To view or add a comment, sign in
-
𝗧𝗵𝗶𝘀 𝗜𝘀 𝗔 𝗟𝗶𝗻𝗸𝗲𝗱𝗜𝗻 𝗣𝗼𝘀𝘁 JavaScript has many small features that can make your code cleaner and easier to maintain. You can use these features to write better code. Here are some tricks to help you: - Remove duplicates from an array with Set - Convert anything to a boolean with double negation - Swap variables with destructuring - Use optional chaining to avoid long nested checks - Provide fallback values easily with ?? - Avoid long nested checks with optional chaining - Use Array.from to create an array from an object - Use flat to flatten an array - Use Object.entries to get an array of key-value pairs - Use Object.fromEntries to create an object from an array - Use at to get the last element of an array - Use filter to remove false values from an array - Use console.table to debug - Use Promise.all to run multiple promises at the same time - Use debounce to delay a function - Use Math.random to generate a unique string - Use includes to check if an array includes a value - Use structuredClone to deep clone an object You can use these tricks to: - Write cleaner code - Reduce boilerplate - Improve readability - Debug faster What's your favorite JavaScript trick? Share it in the comments. Source: https://lnkd.in/gUdrjCvm
To view or add a comment, sign in
-
Most developers think they’re calling pure JavaScript functions. In reality, many of those calls aren’t JavaScript at all. This is where 𝗙𝗮𝗰𝗮𝗱𝗲 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 come in. In architecture, a facade is the simple front of a building—hiding the complex structure behind it. The browser follows the same principle. Functions like `setTimeout`, `fetch`, `document`, `localStorage`, and even `console.log` look like native JavaScript. But they’re actually **interfaces to browser Web APIs**. When you call them, JavaScript delegates the heavy lifting to systems outside the engine: * `setTimeout` → handled by the browser’s timer system * `fetch` → managed by the network layer * `document` → powered by the DOM engine One line of code… but an entire subsystem executes it. Interestingly, not all facade functions behave the same way. For example, `console.log` often executes immediately because debugging requires real-time feedback. Understanding this clears up a lot of confusion around async behavior and performance. It’s no longer “𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗺𝗮𝗴𝗶𝗰”—it’s system design. Here’s how to apply this knowledge: * Recognize which APIs are browser-provided vs pure JS * Don’t assume async behavior—understand how each API works * Use this mental model when debugging unexpected behavior Once you see it, JavaScript becomes far more predictable. Which Web API surprised you the most when you learned it wasn’t actually JavaScript? #JavaScript #WebAPIs #FrontendEngineering #AsyncProgramming #EventLoop #SoftwareEngineering #BrowserInternals #CleanCode
To view or add a comment, sign in
-
-
𝗝𝗮𝗵𝗮 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗦𝘆𝗻𝘁𝗮𝗫, 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁𝘀, 𝗖𝗼𝗺𝗺𝗲𝗻𝘁𝘀 & 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀 JavaScript syntax is a set of rules that define how code must be written. JavaScript is case-sensitive. This means name, Name, and NAME are treated as different things. You use whitespace to make your code readable. - Hard to read: let x=5;let y=10;let z=x+y; - Easy to read: let x = 5; let y = 10; let z = x + y; A statement is a single instruction that tells JavaScript to do something. - let age = 25; declares a variable - console.log(age); prints the value to the console - alert("Hello, World!"); shows a popup in the browser Statements usually end with a semicolon. - let city = "Chennai"; is recommended - let city = "Chennai" also works, but avoid relying on this You can group multiple statements inside curly braces. - if (age > 18) { console.log("Adult"); console.log("Can vote"); } Comments are notes you write in your code. JavaScript ignores them when running the code. - Use // to comment out a single line - Use /* ... */ to comment across multiple lines A variable is like a labelled box - it stores a value that your program can use later. - var is the old way to declare variables - let and const are used in modern JavaScript Variable names must follow these rules: - Must start with a letter, underscore _, or dollar sign $ - Cannot start with a number - Cannot use reserved keywords You can update a variable's value. - var score = 10; - score = 20; updates the value If you declare a variable but don't assign a value, it holds the special value undefined. Key concepts: - Syntax: rules for writing valid JavaScript - Statement: a single instruction - Comment: notes in code ignored by JavaScript - Variable: a named container to store values Source: https://lnkd.in/gmeiXa5P
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