“Why does this behave so weird in JavaScript? 🤯 Let’s finally make sense of it!” If you’ve ever shouted at your screen because this suddenly became undefined — you’re not alone 😅 Let’s break down how this works across different scenarios with simple examples 👇 🧩 1️⃣ Arrow Function Defined Directly in Object const person = { name: "Suverk", greet: () => console.log(`Hi ${this.name}`) }; person.greet(); // ❌ undefined 🧠 Why? Arrow functions don’t have their own this. They lexically inherit this from their surrounding scope — which here is the global (not person). ✅ Fix: Use a regular function: greet() { console.log(`Hi ${this.name}`); } 🧩 2️⃣ Arrow Function Inside a Regular Method const person = { name: "Suverk", greet: function() { const arrow = () => console.log(this.name); arrow(); } }; person.greet(); // ✅ "Suverk" 🧠 Why? The arrow function inherits this from where it was created — inside greet, and this inside greet = person. ✅ Works perfectly because of lexical scoping. 🧩 3️⃣ Regular Function Inside Another Regular Function const person = { name: "Suverk", greet: function() { function inner() { console.log(this.name); } inner(); } }; person.greet(); // ❌ undefined 🧠 Why? When you call inner() as a plain function, it’s not attached to any object. So this defaults to global (or undefined in strict mode). ✅ Fixes: // Option 1 const self = this; function inner() { console.log(self.name); } // Option 2 function inner() { console.log(this.name); } inner.bind(this)(); // Option 3 const inner = () => console.log(this.name); 🧩 4️⃣ Detached Method Reference const person = { name: "Suverk", greet() { console.log(this.name); } }; const use = person.greet; use(); // ❌ undefined 🧠 Why? this depends on how a function is called. You’ve just taken the function reference — the link to person is gone. ✅ Fix: const use = person.greet.bind(person); use(); // ✅ "Suverk" In JavaScript, this depends on how a function is called — except for arrow functions, which depend on where they’re defined. 💬 Have you ever been tricked by this before? Drop your comment below 👇 — let’s make others learn faster than we did 😅 #JavaScript #Frontend #WebDevelopment #Angular
"Understanding JavaScript's this keyword in different scenarios"
More Relevant Posts
-
🚀 WHY CONST AND LET AREN’T LIKE VAR IN JAVASCRIPT If you’ve ever wondered why const “isn’t hoisted”… Here’s the truth 👇 All variables in JavaScript are hoisted, but they’re initialized differently. 🧠 Memory Creation Phase (Before Code Runs) • Keyword Hoisting: Yes, with undefined. • Initialization: Yes. • Access Before Declaration: Allowed, resulting in ReferenceError for `let` and `const`, but undefined for `var`. ReferenceError💡 The time between scope entry and declaration is called the Temporal Dead Zone (TDZ) — the variable exists but can’t be accessed yet. console.log(a); // undefined console.log(b); // ❌ ReferenceError console.log(c); // ❌ ReferenceError var a = 10; let b = 20; const c = 30; ⚙️ What Happens Internally (Visualization) |------------------ JavaScript Execution Context ------------------| | Memory Phase (Hoisting) | var a → undefined | let b → <uninitialized> (TDZ) | const c → <uninitialized> (TDZ) |------------------------------------------------------------------| | Execution Phase | console.log(a) → undefined | console.log(b) → ReferenceError | console.log(c) → ReferenceError | a = 10; b = 20; c = 30; | console.log(a,b,c) → 10 20 30 |------------------------------------------------------------------| ✅ In short: "const and let are hoisted — but remain uninitialized until their declaration is executed." This behavior avoids unexpected bugs and makes JavaScript more predictable 💪 #JavaScript #WebDevelopment #Learning #Programming #CodeNewbie #Frontend
To view or add a comment, sign in
-
Today I revised some of the most essential JavaScript concepts that appear in real-world development. 1️⃣ Higher-Order Function (HOF) ✅ Question: Create a function that runs another function twice 📝 Code: function runTwice(fn) { fn(); fn(); } runTwice(() => console.log("hello")); 🔍 Short Explanation: A HOF is a function that takes another function as input or returns a function. Helps in reusable logic. 2️⃣ Pure Function 📝 Code: function pure(a, b) { console.log(a + b); } pure(2, 3); pure(2, 3); 🔍 Short Explanation: Always gives the same output for the same input. No side effects. 3️⃣ Impure Function 📝 Code: let global = 0; function imPure(a) { global++; console.log(a + global); } imPure(2); imPure(2); 🔍 Short Explanation: Depends on external data → output changes unexpectedly. 4️⃣ Destructuring in Function Parameters 📝 Code: const obj = { name: "Pratik", age: 21 }; function destructuring({ name, age }) { console.log(name, age); } destructuring(obj); 🔍 Short Explanation: Pulls values directly from objects → cleaner code. 5️⃣ Normal Function vs Arrow Function (this difference) 📝 Code: let objTwo = { name: "Pratik", fnc: function () { console.log(this); }, arrowFnc: () => { console.log(this); } }; objTwo.fnc(); objTwo.arrowFnc(); 🔍 Short Explanation: Normal function → owns its own this Arrow function → uses parent this (lexical) 6️⃣ map(): Square each number 📝 Code: let arr = [1, 2, 3, 4, 5]; let newArr = arr.map(e => e * e); console.log(newArr); 🔍 Short Explanation: Transforms each element → returns a new array. 7️⃣ filter(): Get even numbers 📝 Code: let filtered = arr.filter(e => e % 2 === 0); console.log(filtered); 🔍 Short Explanation: Keeps only the elements that match a condition. 8️⃣ reduce(): Total salary 📝 Code: let salary = [10000, 20000, 30000]; let total = salary.reduce((acc, v) => acc + v, 0); console.log(total); 🔍 Short Explanation: Reduces an array into one final value. 9️⃣ some() & every() 📝 Code: let names = ["pratik", "sun", "om", "krish", "vijay"]; let some = names.some(e => e.length > 3); let every = names.every(e => e.length > 3); console.log(some, every); 🔍 Short Explanation: some() → at least ONE matches every() → ALL must match 🔟 Object.freeze() 📝 Code: const users = { name: "Sunny", age: 21 }; Object.freeze(users); users.age = 22; users.city = "Surat"; delete users.name; console.log(users); 🔍 Short Explanation: No add, no delete, no modify → completely locked. 1️⃣1️⃣ Object.seal() 📝 Code: const test = { subject: "Maths", score: 50 }; Object.seal(test); test.score = 60; test.grade = "A"; delete test.subject; console.log(test); 🔍 Short Explanation: You can modify, but cannot add or delete keys. 1️⃣2️⃣ Optional Chaining (?.) 📝 Code: const user = { name: "Pratik", address: { city: "Surat" } }; console.log(user?.address?.city); 🔍 Short Explanation: Avoids errors when accessing nested properties.
To view or add a comment, sign in
-
💭 What do you think — will this effect run on every click? const Counter = () => { const [count, setCount] = React.useState(0); const config = { theme: "dark" }; React.useEffect(() => { console.log("Effect ran"); }, [config]); return <button onClick={() => setCount(count + 1)}>Click</button>; }; At first glance, config looks static. But… this effect will run on every single click 🧨 Let’s break down why — from JavaScript memory to React Fiber internals 👇 🧠 1. JS Basics — Reference Types In JavaScript, objects & functions are reference types — compared by memory address, not content. { a: 1 } === { a: 1 } // false () => {} === () => {} // false Every render recreates: const config = { theme: "dark" } → a new object in memory → a new reference. ⚛️ 2. Under the Hood — React Fiber When setCount triggers a re-render: React creates a new Fiber node for the current render. The previous Fiber is kept as the alternate. React compares them during reconciliation. 🔄 3. Effect Dependency Comparison React checks dependencies via: Object.is(prevDep, nextDep) Since each render creates a new config reference, the comparison fails → effect runs again. 🧩 Render 1 → config ref#1 Render 2 → config ref#2 → Object.is(ref#1, ref#2) → false → Effect runs ⚡️ 🧘♂️ 4. The Fix To prevent unnecessary re-runs, stabilize the reference: const config = React.useMemo(() => ({ theme: "dark" }), []); Or, if it’s static, define it outside the component: const config = { theme: "dark" }; ✅ Summary Each render → new Fiber node New objects/functions → new references React compares deps via Object.is(prev, next) Different refs = effect re-runs Use useMemo / useCallback to stabilize references 🔍 Takeaway: Every render isn’t just new JSX — it’s new memory, new references, and a new Fiber snapshot. Understanding that is what separates debugging React from mastering it. 🚀
To view or add a comment, sign in
-
💛 #JSMadeEasy with Virashree When I first heard about “Hoisting” in JavaScript, I thought it had something to do with lifting variables up 🏋️♀️😂 Turns out… I wasn’t entirely wrong! - Here’s a simple way to understand what Hoisting really means 👇 🧠 What is Hoisting? - When JavaScript runs your code, it does it in two phases: 1️⃣ 𝗠𝗲𝗺𝗼𝗿𝘆 𝗖𝗿𝗲𝗮𝘁𝗶𝗼𝗻 𝗣𝗵𝗮𝘀𝗲 — where it scans and “remembers” all variables and functions 2️⃣ 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗣𝗵𝗮𝘀𝗲 — where it actually runs the code line by line - In the first phase, JS “hoists” (lifts) all variable and function declarations to the top of their scope. 💻 Example 1: Using var console.log(name); // undefined var name = "Virashree"; JS internally does this 👇 var name; // declaration hoisted console.log(name); // undefined name = "Virashree"; - So, name exists in memory but has no value yet — hence undefined. 🌿 Example 2: Using let and const console.log(age); // ❌ ReferenceError let age = 24; - Unlike var, let and const are hoisted too — but they stay in a special zone called the 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲 (𝗧𝗗𝗭) until they’re declared. - That’s why accessing them before declaration throws an error instead of showing undefined. ⚙️ Function Hoisting — Two Types In JavaScript, there are two main ways to create functions: 1️⃣ Function Declaration 2️⃣ Function Expression - And they behave very differently when it comes to hoisting 👇 🌿 1. 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 — Fully Hoisted ✅ The whole function is hoisted to the top of its scope. So you can call it before it’s defined. greet(); // ✅ Works fine function greet() { console.log("Hello, Virashree!"); } ➡️ Output: Hello, Virashree! Because JS hoists both the name and the body of the function. 🌸 2. 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 — NOT Fully Hoisted When you assign a function to a variable (using var, let, or const), only the variable name is hoisted — not the function itself. sayHi(); // ❌ TypeError var sayHi = function() { console.log("Hi there!"); }; - If you used var, you’ll get: ❌ TypeError: sayHi is not a function - If you used let or const, you’ll get: ❌ ReferenceError: Cannot access 'sayHi' before initialization - So basically: 🚫 The variable gets hoisted, but the actual function definition does not. 🧩 Quick Recap var → Hoisted ✅ | Value: undefined let → Hoisted ✅ | Value: ❌ ReferenceError (TDZ) const → Hoisted ✅ | Value: ❌ ReferenceError (TDZ) function decl → ✅ Fully hoisted function expr → ⚠️ Partially hoisted (variable only) 🧠 Takeaway - So next time your code throws “is not a function,” - check how you declared it — not where! 😉 💬 Question for you: Which one confused you more — function declarations or function expressions? Comment below and I’ll break it down in my next #javascript #frontenddevelopment #webdevelopment #reactjs #learninginpublic #womenintech
To view or add a comment, sign in
-
🚀 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: call(), apply(), 𝗮𝗻𝗱 bind() 𝘄𝗶𝘁𝗵 this! Ready to take your JavaScript skills to the next level? 🦸♂️ Understanding this is one of the biggest hurdles for devs, but when you learn how to control it using call(), apply(), and bind(), you'll unlock new superpowers in your code! 🧑💻💥 Let’s break it down with examples that put this in the spotlight: ✨ 1. call() — 𝗧𝗵𝗲 𝗖𝗼𝗻𝘁𝗲𝘅𝘁 𝗖𝗵𝗮𝗻𝗴𝗲𝗿 ⚡ The call() method is like a magic wand that changes the this value to something you specify—𝘢𝘯𝘥 you pass arguments one by one. const person = { name: 'Alice', greet: function(age) { console.log(`Hi, I'm ${this.name} and I'm ${age} years old.`); } }; // Using `call()` to set `this` to `person` and pass arguments individually person.greet.call({ name: 'Bob' }, 25); // Output: "Hi, I'm Bob and I'm 25 years old." 🔑 𝗛𝗼𝘄 𝗜𝘁 𝗪𝗼𝗿𝗸𝘀: Here, this inside greet() is set to { name: 'Bob' }, not the original person object. ✨ 2. apply() — 𝗧𝗵𝗲 𝗔𝗿𝗿𝗮𝘆 𝗟𝗼𝘃𝗲𝗿 🧳 apply() works similarly to call(), but instead of passing arguments one by one, you send them as an 𝗮𝗿𝗿𝗮𝘆. It’s perfect for when you need to handle multiple arguments dynamically! const person = { name: 'Alice', greet: function(city, country) { console.log(`Hi, I'm ${this.name} from ${city}, ${country}.`); } }; // Using `apply()` to pass arguments as an array and change `this` person.greet.apply({ name: 'Charlie' }, ['New York', 'USA']); // Output: "Hi, I'm Charlie from New York, USA." 🔑 𝗛𝗼𝘄 𝗜𝘁 𝗪𝗼𝗿𝗸𝘀: Again, the this context is set to { name: 'Charlie' }, and the arguments ['New York', 'USA'] are passed as an array. ✨ 3. bind() — 𝗧𝗵𝗲 𝗧𝗶𝗺𝗲 𝗧𝗿𝗮𝘃𝗲𝗹𝗲𝗿 ⏳ What if you need to "freeze" a function with a specific this context, but don’t want to call it immediately? That’s what bind() is for. It creates a new function that you can invoke later with a fixed this and pre-set arguments. const person = { name: 'Alice', greet: function(age) { console.log(`Hi, I'm ${this.name} and I'm ${age} years old.`); } }; // Using `bind()` to create a function that is "pre-bound" to `Alice` const greetAlice = person.greet.bind({ name: 'Alice' }); // Later, call the pre-bound function greetAlice(30); // Output: "Hi, I'm Alice and I'm 30 years old." 🔑 𝗛𝗼𝘄 𝗜𝘁 𝗪𝗼𝗿𝗸𝘀: With bind(), this is always set to { name: 'Alice' }, no matter when you call the function! 💡 𝗪𝗵𝘆 𝗬𝗼𝘂 𝗦𝗵𝗼𝘂𝗹𝗱 𝗖𝗮𝗿𝗲: • call() and apply() are perfect for when you want to invoke a function with a specific context immediately, and pass dynamic arguments. • bind() is your go-to for creating "pre-bound" functions that remember their this context when invoked later! #JavaScript #WebDev #CodingTips #JS #TechTalk #WebDevelopment #LearnToCode #DevLife #call #apply #bind
To view or add a comment, sign in
-
JavaScript’s Tricky Trio: call, apply, and bind — Demystified! If you’ve ever been puzzled by these three, you’re not alone. They all revolve around the mysterious this keyword — which sometimes points to the global object, and sometimes to the object that owns the method. Wouldn’t it be great if we could control what this points to? That’s exactly what these methods let us do 👇 🧠 The Big Three 1️⃣ .call() → Invokes the function immediately and lets you pass arguments one by one. 2️⃣ .apply() → Works like .call(), but accepts arguments as an array. 3️⃣ .bind() → Doesn’t execute right away; instead, it creates a new function with a fixed this and preset parameters. 🧩 Example const person = { firstName: "John", lastName: "Doe", getFullName() { return this.firstName + " " + this.lastName; } }; function greet(lang1, lang2) { console.log(`Hello, I am ${this.getFullName()} and I speak ${lang1}, ${lang2}`); } // call → run immediately greet.call(person, "English", "Spanish"); // apply → same, but arguments in an array greet.apply(person, ["French", "German"]); // bind → create a reusable version const greetPerson = greet.bind(person, "Hindi"); greetPerson("Punjabi"); ✅ Output: Hello, I am John Doe and I speak English, Spanish Hello, I am John Doe and I speak French, German Hello, I am John Doe and I speak Hindi, Punjabi ⚙️ Real-world Uses 🔹 Function Borrowing → Use methods from one object on another. 🔹 Function Currying → Create specialized versions of functions with preset parameters. Example: function multiply(a, b) { return a * b; } const multiplyByTwo = multiply.bind(this, 2); console.log(multiplyByTwo(4)); // 8 const multiplyByThree = multiply.bind(this, 3); console.log(multiplyByThree(4)); // 12 🎯 Key takeaway: 👉 .call() & .apply() → Execute now. 👉 .bind() → Save for later (with context pre-set). Once you understand how they work, they stop being scary — and become some of your most powerful tools for mastering function execution in JavaScript. #JavaScript #WebDevelopment #FrontendDevelopment #JS #CodingTips #TechLearning #WebDevCommunity
To view or add a comment, sign in
-
I recently explored how JavaScript’s number type behaves under IEEE 754-and what I found surprised me. While most developers (myself included) focus on ECMAScript compliance, I learned that even standards-compliant code can produce unexpected results in mission-critical systems. Here is what I learned, with real-world examples that show why precision matters. For example, 0.1 + 0.2 === 0.3 returns false in JavaScript due to binary floating-point precision. This is not a bug-it is IEEE 754 doing its job. IEEE 754 in Action: Unsafe comparison const a = 0.1; const b = 0.2; const sum = a + b; console.log(sum); // 0.30000000000000004 console.log(sum === 0.3); // false Safe Comparison Using Tolerance function nearlyEqual(x, y, epsilon = 1e-10) { return Math.abs(x - y) < epsilon; } console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true This method checks if two numbers are close enough, which is the recommended approach for comparing floats. Safer Arithmetic with Integers const priceCents = 10 + 20; // 0.1 + 0.2 -> 10 + 20 const totalCents = priceCents * 100; // 3000 console.log(totalCents / 100); // 30 Use integers for money, counts, and critical logic to avoid rounding surprises. Decimal Libraries for Precision HTML <script type="module"> import Decimal from ''https://lnkd.in/gi4T53Fe'; const x = new Decimal('0.1'); const y = new Decimal('0.2'); const z = x.plus(y); console.log(z.toString()); // "0.3" </script> /* Use Node.js with ES Modules If you're using Node.js, either: Rename your file to .mjs Or add "type": "module" to your package.json */ import Decimal from 'decimal.js'; const x = new Decimal('0.1'); const y = new Decimal('0.2'); const z = x.plus(y); console.log(z.toString()); // "0.3" // Use require() in CommonJS (Node.js) const Decimal = require('decimal.js'); const x = new Decimal('0.1'); const y = new Decimal('0.2'); const z = x.plus(y); console.log(z.toString()); // "0.3" Libraries like decimal.js or Big.js offer exact decimal arithmetic, ideal for financial and mission-critical applications. This got me curious about real-world consequences of precision loss. I came across examples like: Patriot Missile Failure (1991): 0.34 sec drift due to rounding -> 28 lives lost Ariane 5 Rocket Explosion (1996): float-to-int overflow -> $370M loss Knight Capital (2012): float error in trading logic -> $440M loss in 45 mins Medical devices: insulin pumps miscalculating dosage due to float rounding These are not edge cases-they are reminders that even basic arithmetic can be dangerous in the wrong context. I am not an IoT or finance expert, but this learning made me rethink how I handle numbers in code. For critical logic, I now prefer: Using integers (e.g., cents instead of dollars) Leveraging BigInt or libraries like decimal.js Adding runtime checks for IEEE 754 compliance Avoiding implicit float-to-int conversions Have you ever run into float precision issues in your own projects?
To view or add a comment, sign in
-
JavaScript evolves every year — but many devs still use it like it’s 2016. 🚀 Here are 5 underrated modern features that can simplify your code instantly: Optional chaining ?. Nullish coalescing ?? Array.at() Object.hasOwn() Intl for formatting 1️⃣ Optional Chaining (?.) 💡 Use Case: Access nested properties safely without breaking your code. const user = { profile: { name: 'Akhila' } }; console.log(user.profile?.name); // ✅ 'Akhila' console.log(user.address?.city); // ✅ undefined (no error) 🧠 No more Cannot read property 'x' of undefined errors. 2️⃣ Nullish Coalescing (??) 💡 Use Case: Provide fallback values only for null or undefined. const score = 0; console.log(score ?? 100); // ✅ 0 (unlike || which would return 100) ⚡ Keeps false, 0, and '' valid — great for numeric or boolean defaults. 3️⃣ Array.at() 💡 Use Case: Access elements from the end of an array more cleanly. const fruits = ['🍎', '🍌', '🍇']; console.log(fruits.at(-1)); // ✅ '🍇' (last element) 🍉 Replaces clunky fruits[fruits.length - 1] syntax. 4️⃣ Object.hasOwn() 💡 Use Case: Check if an object directly has a property (safer than hasOwnProperty). const obj = { name: 'JS' }; console.log(Object.hasOwn(obj, 'name')); // ✅ true 🛡️ Cleaner and avoids prototype pollution issues. 5️⃣ Intl (Internationalization API) 💡 Use Case: Format dates, numbers, and currencies globally. const price = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(9999.5); console.log(price); // ✅ ₹9,999.50 🌍 Perfect for apps with multi-language or multi-region users. ✨ Small features, big clarity. Which of these do you use the most (or plan to start using)? #JavaScript #WebDevelopment #CodingTips #Frontend #TechTrends
To view or add a comment, sign in
-
-
#9: From Loop Newbie to Array Method Pro in JavaScript! 🚀 Today’s journey took me from basic loops to mastering powerful array methods. If you’ve ever wondered when to use for…of, for…in, forEach, map, filter, or reduce — this post is for YOU 👇 🔁 1. for…of – Best for Iterating Over Iterables (Array / Map) ✅ Returns full value ✅ Can use destructuring in Maps for (const [key, value] of myMap) { console.log(key, value); } ❌ Doesn’t work on plain objects (not iterable). 📍 2. for…in – Works on Objects & Arrays (Keys Only) ✅ Best for objects: for (const key in myObject) { console.log(key, myObject[key]); } ⚠ On arrays, it gives indexes, not values. ❌ Doesn’t work on Map. 📦 3. forEach() – Simple, Clean, No Return ✅ Great for looping arrays ✅ Accepts callback (value, index, array) ✅ Can pass an external function coding.forEach((item, index, arr) => console.log(item, index)); ❌ Doesn’t return anything (undefined always). 🗺️ 4. map() – Returns a New Array ✅ 🔹 Used when you want to transform data. const newArr = nums.map(num => num * 2); ✅ map() → RETURNS ❌ forEach() → DOES NOT RETURN 🧽 5. filter() – Keeps Only What Matches ✅ 🔍 Creates an array based on a condition. const filtered = nums.filter(num => num > 4); ✅ Returns only items that meet criteria. ⛓️ 6. Method Chaining = Cleaner Power Moves ⚡ const result = nums .map(num => num * 10) .map(num => num + 1) .filter(num => num > 50); 📉 7. reduce() – Converts Everything to a Single Value Used for totals, sums, or combining data. const total = prices.reduce((acc, curr) => acc + curr, 0); ✅ Perfect for shopping cart totals, analytics, etc. 🎯 Where You Stand Now: Level → Concept 🟢 Beginner → for...in, for...of 🟡 Intermediate → forEach, map, filter 🔴 Pro → reduce, chaining, destructuring in loops ✨My Takeaway: Once you understand array methods like map, filter, and reduce, you write less code, cleaner logic, and think more like a JavaScript pro. 💡 🧠 Which one confused you the most when you started learning loops in JS? Comment below — let’s grow together! 👇🔥 #JavaScript #WebDevelopment #LearningEveryday #Frontend
To view or add a comment, sign in
-
Why Did 5 + "5" Give You 55 🤓? Let’s Talk About JS Type Coercion This explanation is going to make you understand why [ ] == ![ ] is equal to true If you’ve ever typed 5 + "5" in JavaScript and got "55" instead of 10, don’t worry, you didn’t break anything. You just bumped into something called Type Coercion. It’s one of those sneaky but important concepts in JavaScript that can either save you or confuse you if you don’t understand how it works. Let’s break it down together in the simplest way. So, What Is Type Coercion? JavaScript is what we call a “loosely typed” language. This means it lets you mix and match data types (like strings, numbers, booleans), and it tries to convert them automatically when needed. This automatic conversion is known as Type Coercion. It happens all the time behind the scenes, sometimes in helpful ways, sometimes in surprising ones. Two Types: Implicit and Explicit There are two main types of coercion: Implicit coercion happens when JavaScript does the converting for you (without asking). Explicit coercion happens when you do the converting on purpose using methods like String(), Number(), or Boolean(). Let’s Look at Some Real Examples ✅ Here are a few common cases where coercion shows up: ✅ 5 + "5" → "55" (number becomes a string, because + with a string means concatenate) ✅ "10" - 3 → 7 (string becomes a number, because - only works with numbers) ✅ true + 1 → 2 (boolean true becomes 1) ✅ false == 0 → true (loose equality == allows coercion) ✅ null == undefined → true (but they’re not strictly equal!) ✅ [] + 1 → "1" (array becomes an empty string, then it's concatenated) ✅ [1] + 1 → "11" (array [1] becomes "1", then string + number = string) Understand how JavaScript behaves with different value types is very crucial for building effective and bug free scalable applications. But nevertheless, you wehther you know type Coercion or not, it's always better you take precautions. How to Keep Your Code Clean and Safe To avoid surprises, always try to use strict equality (===) instead of ==, because it checks both value and type. Also, manually convert data to the correct type when needed using Number(), String(), or Boolean(). This gives you more control and fewer headaches down the line. I hope you have learnt something.
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