💡 “this” in JavaScript - It’s All About Context 😎 Have you ever written console.log(this) and got something completely unexpected? 😅 You’re not alone every JavaScript developer has been confused by this at least once. But here’s the thing 👇 this isn’t confusing… it’s just based on where you use it. Let’s break it down simply 👇 🌍 In the Global or Function Scope: When you use this outside of any object or function, it refers to the global object in a browser, that’s usually the window object. 🧩 Inside an Object Method: When this is used inside an object’s method, it points to that object itself. It basically says, “I belong to this object.” ⚡ Inside an Arrow Function: Arrow functions don’t have their own this. They automatically take this from the outer (parent) scope where they were defined. That means if an arrow function is inside another function or object, it uses that parent’s this. 🎯 In Event Handlers: When used inside a regular function event handler, this points to the DOM element that triggered the event. Example: button.addEventListener("click", function() { console.log(this); // The button element }); 🧠 So, what’s the main idea? this always depends on how and where it’s used — not just where it’s written. It changes its meaning based on the context it’s in. 💬 Next time JavaScript surprises you with this, remember — it’s not broken… it’s just context-aware. Have you ever been confused by this before? #JavaScript #WebDevelopment #Frontend #CodingTips #LearnInPublic #100DaysOfCode
Understanding "this" in JavaScript: A Context Guide
More Relevant Posts
-
🎯 JavaScript Scope — The Invisible Boundary of Your Code! Have you ever written some JavaScript and suddenly got an error like: ❌ “variable is not defined” — even though you did define it? 😅 That’s the power (and sometimes the confusion) of Scope in JavaScript! --- 🧠 What is Scope? Scope simply means “where a variable is accessible in your code.” It determines which parts of your program can see or use a variable. Think of scope like a fence 🏡 — variables inside the fence can’t just wander outside unless they’re allowed to. --- 💡 Types of JavaScript Scope: 1️⃣ Global Scope 🌍 Variables declared outside any function or block. They can be used anywhere in your code. let name = "Azeez"; console.log(name); // Accessible everywhere 2️⃣ Function Scope 🧩 Variables declared inside a function are only visible inside that function. function greet() { let message = "Hello!"; console.log(message); // Works fine here } console.log(message); // ❌ Error! Not defined 3️⃣ Block Scope 🔒 Introduced with let and const — variables declared inside {} are only accessible within that block. if (true) { let food = "Pizza"; console.log(food); // Works } console.log(food); // ❌ Not accessible --- ⚡ Why Scope Matters: ✅ It prevents variable name conflicts ✅ It keeps your code organized and clean ✅ It improves memory management --- 💬 Quick Tip: Always use let and const instead of var — because var ignores block scope and can cause tricky bugs 🐛. --- 🚀 In short: Scope defines where your variables live and how far they can travel. Keep them in their lane, and your code will stay clean and bug-free! 😎 #codecraftbyaderemi #webdeveloper #frontend #webdevelopment #javascript #webdev
To view or add a comment, sign in
-
-
Have you ever tried sorting numbers in JavaScript and it just gives you nonsense? 😒 Like, you do [200, 100, 5].sort() and it returns [100, 200, 5] That’s because JavaScript, by default, sorts everything as strings, not actual numbers. So it’s basically going, “Hmm, 100 starts with a 1, that must come first.” To fix that and sort numbers properly in ascending order (smallest to biggest), just add a compare function: array.sort((a, b) => a - b) This basically tells JavaScript to compare each pair of values in the array by subtracting one from the other. If the result is negative, it means a is smaller than b, so JavaScript keeps a before b. If the result is positive, b is smaller, so it gets placed before a. And if the result is zero, it means they’re equal, and the order stays the same. This allows the sort method to arrange the numbers from smallest to largest unlike the default .sort() which treats numbers like strings and messes up the order. Now if you want to sort in descending order (biggest to smallest), just flip it: array.sort((a, b) => b - a) Sorting in descending order is especially useful when you're dealing with scores, prices, rankings, or anytime the biggest number should be on top. Once you understand what a and b are doing in that function, sorting becomes super easy and honestly, kind of satisfying. You can even write your own custom sort function which you can call anytime you want to sort anything in your program. Checkout my custom sort function in the image below and tell me what you think. I made it to work in thesame way as the sort() method. The code snippet will give you an understanding of what happens under the hood when you use the sort() method. Make sure you check it out. I hope you have learnt something from this post😃
To view or add a comment, sign in
-
-
🚀 JavaScript Hoisting — “It’s not magic, it’s just how JS works!” ✨ Ever seen your code work even before you declared a variable or function? That’s not sorcery, that’s Hoisting 😎 ⸻ 🧠 What is Hoisting? In simple terms — JavaScript moves declarations (not initializations) to the top of their scope before execution. Let’s see how 👇 ⸻ 🧩 Example 1: var is hoisted but initialized as undefined console.log(name); // ❓ undefined var name = "Vivek"; Behind the scenes: var name; console.log(name); // undefined name = "Vivek"; 🧠 JS declares the variable first, then runs your code line by line. ⸻ 🧩 Example 2: let and const are hoisted too — but they live in the ⚠️ Temporal Dead Zone console.log(age); // ❌ ReferenceError let age = 25; They’re hoisted but not initialized, so you can’t access them before the declaration line. ⸻ 🧩 Example 3: Functions get fully hoisted! sayHello(); // ✅ Works fine! function sayHello() { console.log("Hello World!"); } 🧠 Function declarations are hoisted with their definitions, while function expressions are not: greet(); // ❌ TypeError var greet = function() { console.log("Hi!"); }; ⸻ 💬 Pro Tip: Always declare your variables before using them — not because you have to, but because your future self will thank you later 😅 ⸻ #JavaScript #WebDevelopment #Frontend #CodingTips #ReactJS #Hoisting
To view or add a comment, sign in
-
-
Are you writing clean, high-performance JavaScript? 🚀 Stop making these common mistakes! This guide is packed with essential JS best practices to instantly level up your code quality and speed: -> Ditch var 🚫: Always use let and const to declare variables to prevent scope and redefinition errors. -> Optimize Loops ⏱️: Boost performance by reducing activity inside loops, like calculating array length once outside the loop. -> Minimize DOM Access 🐌: Accessing the HTML DOM is slow. Grab elements once and store them in a local variable if you need to access them multiple times. -> Use defer ⚡: For external scripts, use the defer attribute in the script tag to ensure the script executes only after the page has finished parsing. -> Meaningful Names ✍️: Use descriptive names like userName instead of cryptic ones like un or usrnm for better long-term readability. -> Be Thoughtful about Declarations 💡: Avoid unnecessary declarations; only declare when strictly needed to promote proper code design. Swipe and save these tips for cleaner, faster JS code! Which practice are you implementing first? 👇 To learn more about JavaScript, follow JavaScript Mastery #JavaScript #JS #WebDevelopment #CodingTips #Performance #CleanCode #DeveloperLife #TechSkills
To view or add a comment, sign in
-
Are you writing clean, high-performance JavaScript? 🚀 Stop making these common mistakes! This guide is packed with essential JS best practices to instantly level up your code quality and speed: -> Ditch var 🚫: Always use let and const to declare variables to prevent scope and redefinition errors. -> Optimize Loops ⏱️: Boost performance by reducing activity inside loops, like calculating array length once outside the loop. -> Minimize DOM Access 🐌: Accessing the HTML DOM is slow. Grab elements once and store them in a local variable if you need to access them multiple times. -> Use defer ⚡: For external scripts, use the defer attribute in the script tag to ensure the script executes only after the page has finished parsing. -> Meaningful Names ✍️: Use descriptive names like userName instead of cryptic ones like un or usrnm for better long-term readability. -> Be Thoughtful about Declarations 💡: Avoid unnecessary declarations; only declare when strictly needed to promote proper code design. Swipe and save these tips for cleaner, faster JS code! Which practice are you implementing first? 👇 To learn more about JavaScript, follow JavaScript Mastery #JavaScript #JS #WebDevelopment #CodingTips #Performance #CleanCode #DeveloperLife #TechSkills
To view or add a comment, sign in
-
# Today I Learned: JavaScript Operators ----------------------------------------------- Today, I explored three important types of JavaScript operators — Logical, Bitwise, and Ternary. Here’s a quick summary with examples 👇 ------------------------------------------ 1. Logical Operators ----------------------- Used to combine multiple conditions or make decisions. EXAMPLES -------------------- let a = 10 b = 5; console.log(a > 5 && b < 10); // true → AND console.log(a > 5 || b > 10); // true → OR console.log(!(a > 5)); // false → NOT 2. Bitwise Operators ------------------------- These work on binary numbers at the bit level — useful in performance-based tasks. let x = 5; // (0101) let y = 1; // (0001) console.log(x & y); // 1 → AND console.log(x | y); // 5 → OR console.log(x ^ y); // 4 → XOR console.log(~x); // -6 → NOT 3. Ternary Operator ------------------ A short and clean way to write conditional statements. let age = 20; let status = (age >= 18) ? "Adult" : "Minor"; console.log(status); // "Adult" #10000coders #javascript
To view or add a comment, sign in
-
💡 JavaScript: The Little Things That Fool Even Experienced Devs (Day 6/50) Ever debugged something in JavaScript that made zero sense — but later realized it was 100% logical once you understood what was happening? 😅 Let’s uncover 3 of those sneaky concepts 👇 --- ⚙️ 1️⃣ Promises vs setTimeout — Who runs first? Even if both have a 0ms delay, Promises (microtasks) run before setTimeout (macrotasks). That’s how the JavaScript Event Loop works — it always clears the microtask queue first. So, when debugging async code, remember: ✅ Promises first, then timers later. --- 🧩 2️⃣ Objects as Keys — The Silent Overwrite When you use objects as keys inside another object, JavaScript doesn’t treat them as unique objects. It converts them to the string "[object Object]". So your carefully separated keys might actually overwrite each other 😬 If you really need objects as keys → use a Map, not a plain object. --- 🎯 3️⃣ The “this” Trap in Arrow Functions Arrow functions don’t have their own this. They inherit it from the surrounding scope. That’s why this inside an arrow function often points to the wrong place (like window or undefined) — while a regular function gets its own this when called. 👉 Moral: Use normal functions when you want this to refer to your object. --- ✨ Takeaway: It’s these small but powerful details that make JavaScript fun — and frustrating 😄 Mastering them means you’re not just writing code… you’re understanding it. --- 🎥 We covered these with real code examples in Day 6 of our “50 Days of JavaScript Tricky Interview Questions” series! Watch here 👉 https://lnkd.in/g5_bPcur #javascript #webdevelopment #frontenddeveloper #backenddeveloper #asyncjavascript #eventloop #thiskeyword #objectkeys #codinginterview #learnjavascript #fullstackdeveloper #techsharingan
To view or add a comment, sign in
-
In frontend development, mastering event handling is crucial for performance. This article provides a technical guide to implementing Debouncing and Throttling in JavaScript to optimize resource-intensive operations. https://lnkd.in/eDxqCdpX #javascript #debounce #throttle #webperformance #codewolfy
To view or add a comment, sign in
-
Templates in JavaScript: JavaScript Feature Spotlight: Template Literals & Tagged Templates Writing clean and dynamic strings in JavaScript has never been easier! Let’s explore Template Literals and Tagged Templates. Template Literals Template literals use backticks (`) to embed variables and expressions directly inside strings: const name = "Sameer"; console.log(`Hello, ${name}! Welcome to LinkedIn.`); // Hello, Sameer! Welcome to LinkedIn. No more messy concatenation with +! Tagged Templates Tagged templates give you more power—they allow a function to process a template literal before outputting it. function highlight(strings, name) { return `${strings[0]} **${name}**!`; } const name = "Sameer"; console.log(highlight`Hello, ${name}`); // Hello, **Sameer**! Perfect for custom formatting, localization, or security (like sanitizing inputs). Pro Tip: Tagged templates are underused but incredibly powerful for building dynamic and safe strings in your apps. #JavaScript #WebDevelopment #Frontend #TemplateLiterals #TaggedTemplates #CodingTips #CleanCode #DevCommunity
To view or add a comment, sign in
-
⚙️ Understanding Hoisting & Temporal Dead Zone (TDZ) in JavaScript I explored two important JavaScript concepts that often confuse developers — Hoisting and Temporal Dead Zone (TDZ). Both are related to how JavaScript handles variable and function declarations during the compilation phase before code execution. 🔹 What is Hoisting? Hoisting is JavaScript’s default behavior of moving declarations to the top of their scope (global or functional) before code execution. In simple terms: You can use variables or functions before declaring them — because declarations are hoisted to the top internally. ✅ Function declarations are fully hoisted — both name and body are moved to the top of their scope. 🔹 Temporal Dead Zone (TDZ) The Temporal Dead Zone occurs when a variable is declared using let or const but is accessed before its declaration. This happens because, even though let and const are hoisted, they remain uninitialized in a special zone (TDZ) until the code execution reaches their line. Here, a exists in memory but is inaccessible until the declaration line is executed — this duration is called the Temporal Dead Zone. ✅ With var, the variable is hoisted and initialized as undefined. ❌ With let and const, the variable is hoisted but not initialized — hence TDZ applies. 💡 Why It Matters ==> Helps understand execution context creation in JavaScript. ==> Prevents common runtime errors like Reference Error. ==> Encourages using let and const for cleaner, safer code practices. #JavaScript #WebDevelopment #CodingJourney #Frontend #ProgrammingConcepts #Hoisting #TemporalDeadZone #LearnToCode
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