Yesterday, I went deeper into one of the most confusing parts of JavaScript: "The + operator" At first glance, `+` looks simple. But unlike operators such as -, *, and /, JavaScript’s + has two possible meanings: - numeric addition - string concatenation And that is exactly what makes it tricky. My biggest takeaway was this: 1. When JavaScript sees a + b, it does not immediately assume numeric addition. 2. It first has to decide: - Should this be string concatenation? - Or should this be numeric addition? That decision is what makes "+" so different from operators like "-". For example: - "5" - 1 gives 4 because subtraction is numeric only. But: - "5" + 1 gives "51" because once JavaScript sees that one side becomes a string, it goes down the string concatenation path. I also learned that the real logic of + is deeper than the small operator section most people look at first. The actual mental model I now use is: 1. Convert both sides to primitives 2. If either primitive is a string: - convert both to strings - concatenate Otherwise: - convert both to numeric values - make sure the numeric types match - perform numeric addition That also led me into learning ToNumeric, which was another big insight. Before this, I mostly thought in terms of ToNumber, but ToNumeric is different: - ToNumber only gives a Number - ToNumeric can return either a Number or a BigInt That is why: - 1n + 2n works but - 1 + 2n throws a TypeError because JavaScript does not allow mixing Number and BigInt in that numeric path. The more I study coercion, the more I realise that JavaScript is not random at all. A lot of “weird” behavior starts making sense when you stop memorising examples and instead ask: - what operation is being performed? - what kind of value does it need? - which abstract operation is JavaScript using behind the scenes? That shift in mindset is making the language far more understandable for me. I’ve also been maintaining detailed notes on everything I’m learning. If anyone wants the deeper breakdown with examples and spec-based notes, I’ve uploaded them here: GitHub repo: https://lnkd.in/ephuZ-w6 Next, I’ll keep going deeper into coercion and loose equality. #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript #100DaysOfCode
JavaScript's + Operator: A Deeper Look
More Relevant Posts
-
Lately, I’ve been going deeper into JavaScript coercion, and the more I study it, the less random JavaScript feels. A lot of behaviour that looks strange at first starts making sense once you realise that JavaScript is following rules defined in the ECMAScript specification. Recently, I focused on the abstract operations behind conversion, especially: - ToNumber - StringToNumber - ToString - ToPrimitive - OrdinaryToPrimitive One of the biggest takeaways for me is that JavaScript does not just “guess” what to do with values. It follows a defined process depending on the operation being performed. For example: - `"5" - 1` works because subtraction expects numbers. - `Number("")` becomes `0`. - `Number(undefined)` becomes `NaN`. - `ToNumber(BigInt)` throws an error, but `ToString(BigInt)` works. - When an object is involved, JS first tries to extract a primitive value before continuing coercion The part I found especially interesting was object-to-primitive conversion. If JavaScript encounters an object in a coercion context, it first checks for `Symbol.toPrimitive`. If that is not available, it falls back to `OrdinaryToPrimitive`, where the order of calling `toString()` and `valueOf()` depends on the hint being used: - string hint → toString() first - number hint → valueOf() first I also learned more about why string-to-number conversion behaves the way it does: - Number("25") gives 25 - Number(" 25 ") also gives 25 - Number("Infinity") gives Infinity - Number("1_000") gives NaN - Number("10n") gives NaN What is changing my understanding the most is this: - Instead of memorising “weird JavaScript behaviour”, I’m now trying to ask: 1. What operation is being performed? 2. What type of value does that operation expect? 3. Which abstract operation is JavaScript using behind the scenes? That mindset makes the language much easier to reason about. I’ve also been maintaining detailed notes on what I’m learning. If anyone wants to go deeper into these topics, I’ve uploaded them here: GitHub repo: https://lnkd.in/ephuZ-w6 #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 26 You click a button… But nothing happens immediately 😳 Instead… it waits. Then suddenly → response comes. How does JavaScript handle this? 🤔 🔥 The Problem JavaScript runs line by line (synchronously) console.log("Start") console.log("Process") console.log("End") 👉 Output: Start Process End Everything runs one after another 😵 But Real World is Different Think about: 👉 API calls 👉 File loading 👉 Timers They take time ⏳ If JavaScript waits… everything will freeze ❌ 🔥 Solution → Asynchronous JavaScript JavaScript can handle tasks without blocking execution 🔹 Example with setTimeout console.log("Start") setTimeout(() => { console.log("Delayed Task") }, 2000) console.log("End") 👉 Output: Start End Delayed Task 🔍 What’s happening? 👉 setTimeout runs later 👉 JavaScript doesn’t wait 👉 Code continues execution 🔹 Callback in Async setTimeout(function() { console.log("Task Done") }, 1000) 👉 Function runs after delay 📌 This function is a callback 🔥 Real Life Example Ordering food 🍔 You order → wait Meanwhile → you do other work Food arrives later 👉 That’s async behavior 🔥 Simple Summary Sync → line by line execution Async → non-blocking execution Callback → function runs later 💡 Programming Rule Don’t block execution. Let JavaScript handle tasks asynchronously. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript (Callbacks) Day 27 → Promises (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 Day 3 of #30DaysOfJavaScript (27 April 2026) Today I learned All types of Conditionals in JavaScript আজ আমি JavaScript-এর সব ধরনের Conditionals শিখেছি 📌 Conditionals (Definition | সংজ্ঞা) 👉 Conditionals are used to control the flow of a program based on conditions. 👉 Conditionals হলো এমন logic যেটা condition অনুযায়ী program-এর flow control করে।🔹 1. if Statement (Basic Condition) 👉 Runs code only if condition is true 👉 শুধু condition true হলে কাজ করে let age = 18; if (age >= 18) { console.log("Adult"); } 🔸 2. if...else Statement 👉 One block runs if true, another if false 👉 true হলে একটা, false হলে অন্যটা let age = 16; if (age >= 18) { console.log("Adult"); } else { console.log("Not Adult"); } 🔹 3. else if Ladder (Multiple Conditions) 👉 Used when multiple conditions exist 👉 একাধিক condition check করার জন্য let marks = 75; if (marks >= 80) { console.log("A+"); } else if (marks >= 60) { console.log("A"); } else { console.log("Fail"); } 🔁 4. switch Statement (Fixed Cases) 👉 Used for multiple fixed value checks 👉 fixed value compare করার জন্য let day = "Monday"; switch (day) { case "Monday": console.log("Start Week"); break; case "Friday": console.log("Weekend Coming"); break; default: console.log("Normal Day"); } ⚡ 5. Ternary Operator (Shortcut Condition) 👉 Short form of if...else 👉 ছোটভাবে condition লেখার shortcut let age = 20; let result = (age >= 18) ? "Adult" : "Not Adult"; ⚠️ Common Mistake 👉 Forgetting break in switch 👉 Complex logic in ternary makes code unreadable 🔥 Learning 👉 Conditionals are the core of decision-making in programming 👉 Programming logic build korar base holo conditionals #JavaScript #FullStackDeveloper #LearningInPublic #WebDevelopment #30DaysChallenge
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 28 Promises made async code better… But still… something feels messy 😵 👉 Too many .then() 👉 Hard to read 👉 Looks like chaining hell What if async code could look like normal synchronous code? 🤔 🔥 Solution → Async / Await 🔹 The Problem with Promises fetchData() .then(data => { console.log(data) return processData(data) }) .then(result => { console.log(result) }) .catch(err => console.log(err)) 👉 Works… but not clean ❌ 🔹 Async / Await (Cleaner Way) async function handleData() { try { let data = await fetchData() console.log(data) let result = await processData(data) console.log(result) } catch (err) { console.log(err) } } handleData() 👉 Looks simple & readable ✅ 🔍 What is happening? 👉 async → function always returns a promise 👉 await → waits for promise to resolve 🔹 Example function fetchData() { return new Promise(resolve => { setTimeout(() => { resolve("Data received") }, 2000) }) } async function getData() { let data = await fetchData() console.log(data) } getData() 👉 Output: Data received 🔥 Real Life Example Think of cooking 🍳 👉 Order ingredients 👉 Wait for delivery 👉 Then cook With async/await: Step by step… clean and clear 🔥 Simple Summary async → makes function async await → waits for result Result → clean & readable code 💡 Programming Rule Write async code like sync code. Clarity > complexity. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 23 A website without interaction is boring… 😴 No clicks No input No response Just static content ❌ 🤔 Real Question How does a website know… 👉 When you click a button? 👉 When you type in an input? 👉 When you scroll? This is where Events come in. 🔥 What is an Event? An event is something that happens in the browser 👉 Click 👉 Hover 👉 Key press 👉 Scroll JavaScript listens to these events and reacts. 🔹 Adding an Event Listener let button = document.querySelector("button") button.addEventListener("click", function() { console.log("Button Clicked") }) 👉 When user clicks → function runs 🔹 Common Events // Click button.addEventListener("click", fn) // Input input.addEventListener("input", fn) // Key press document.addEventListener("keydown", fn) 🔹 Real Example let btn = document.querySelector("button") let heading = document.querySelector("h1") btn.addEventListener("click", function() { heading.innerText = "You clicked the button!" }) 👉 Click → text change 😎 🔹 Event Object JavaScript automatically gives event details button.addEventListener("click", function(event) { console.log(event) }) 📌 You get info like: 👉 Mouse position 👉 Target element 👉 Key pressed 🔥 Real Life Example Think of a doorbell 🔔 You press → sound comes 👉 Action → Reaction Same in JS: User action → Event → Response 🔥 Simple Summary Event → user action addEventListener → listen to event function → response 💡 Programming Rule Websites react to users. Events make that possible. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 JavaScript Hoisting 💥 JavaScript Hoisting Explained: Why Your Code Breaks Before It Runs 👉 Hoisting is JavaScript's behavior of moving declarations to top of their scope during execution. 🔹 1. What Gets Hoisted? - var: Hoisted, initialized as undefined - let: Hoisted, not initialized (TDZ) - const: Hoisted, not initialized (TDZ) - function: Fully hoisted 🔹 2. Variable Hoisting (var) console.log(x); var x = 5; 👉 Output: undefined 👉 Behind the scenes: var x; console.log(x); // undefined x = 5; 🔹 3. let & const Hoisting (TDZ) console.log(a); let a = 10; 👉 Output: ReferenceError 👉 Why? Because of Temporal Dead Zone (TDZ) 👉 Variable exists but cannot be accessed before declaration 🔹 4. Function Hoisting ✅ Function Declaration (Fully Hoisted) greet(); function greet(){ console.log("Hello"); } 👉 Works perfectly ❌ Function Expression (Not Fully Hoisted) greet(); var greet = function(){ console.log("Hello"); } 👉 Output: TypeError: greet is not a function 🔹 5. Temporal Dead Zone (TDZ) 👉 Time between: Variable hoisted Variable declared During this time → ❌ cannot access variable { console.log(x); // ❌ Error let x = 5; } 🔹 6. Common Mistakes ❌ Using variables before declaration ❌ Confusing var with let ❌ Assuming all functions behave the same ⭐ Most Important Points ✅ var → hoisted with undefined ✅ let/const → hoisted but in TDZ ✅ Function declarations → fully hoisted ✅ Function expressions → not fully hoisted 🎯 Quick Summary - JavaScript moves declarations up, not values - var → usable before declaration (but undefined) - let/const → cannot use before declaration - Functions → behave differently based on type If this finally made hoisting click for you… 👉 Drop a ❤️ and comment "HOISTED" 👉 Follow Mohd Sharfuddin Khan for more bite-sized dev concepts that actually make sense
To view or add a comment, sign in
-
🚀 𝗟𝗲𝘃𝗲𝗹𝗶𝗻𝗴 𝘂𝗽 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗿𝗲𝗮𝗱𝗮𝗯𝗶𝗹𝗶𝘁𝘆 𝘄𝗶𝘁𝗵 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 String concatenation in JavaScript can quickly turn messy—especially as logic scales. That’s where template literals step in and change the game. I've put together a detailed blog breaking this down: “𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗦𝗮𝘆 𝗚𝗼𝗼𝗱𝗯𝘆𝗲 𝘁𝗼 𝗦𝘁𝗿𝗶𝗻𝗴 𝗖𝗼𝗻𝗰𝗮𝘁𝗲𝗻𝗮𝘁𝗶𝗼𝗻 𝗡𝗶𝗴𝗵𝘁𝗺𝗮𝗿𝗲𝘀” Link: https://lnkd.in/dQdeSyxh 🔍 What the blog covers: 🔹 Why traditional string concatenation becomes hard to maintain 🔹 How template literals improve readability and developer experience 🔹 Practical use-cases with expressions and multi-line strings 🔹 Writing cleaner, more scalable JavaScript code If you're working with JavaScript, this is a small shift that delivers a big productivity gain. Grateful for the continuous learning ecosystem and guidance from: Hitesh Choudhary Piyush Garg Anirudh J. Chai Aur Code Akash Kadlag Suraj Kumar Jha Nikhil Rathore Jay Kadlag DEV Community #JavaScript #WebDevelopment #TechnicalWriting #CleanCode #LearningInPublic #Chaicode #Cohort
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 30 JavaScript feels fast… But have you ever wondered 👇 👉 How does it handle multiple tasks at once? 👉 How does async code run without blocking? This is where the **Event Loop** comes in 😎 --- ## 🤯 The Big Confusion JavaScript is **single-threaded** 👉 It can do **one thing at a time** Then how does this work? 👇 ```javascript id="el1" console.log("Start") setTimeout(() => { console.log("Async Task") }, 0) console.log("End") ``` 👉 Output: Start End Async Task Wait… why? 🤔 --- ## 🔥 Behind the Scenes JavaScript has 3 main parts: 👉 Call Stack 👉 Web APIs 👉 Callback Queue --- ## 🔹 Step by Step Flow 1️⃣ `console.log("Start")` → runs first 2️⃣ `setTimeout` → goes to **Web API** 3️⃣ `console.log("End")` → runs next 4️⃣ Callback goes to **Queue** 5️⃣ Event Loop checks → stack empty? 6️⃣ Yes → push callback to stack 👉 Then runs → "Async Task" --- ## 🔍 Visualization ```id="viz1" Call Stack → Executes code Web APIs → Handles async tasks Queue → Stores callbacks Event Loop → Manages everything ``` --- ## 🔥 Real Life Example Think of a **restaurant 🍽️** 👉 Waiter takes order → sends to kitchen 👉 Kitchen prepares food 👉 Meanwhile waiter serves others 👉 When food is ready → serves you 👉 Event Loop = waiter managing tasks --- ## 🔥 Simple Summary JS → single-threaded Async → handled outside Event Loop → manages execution --- ### 💡 Programming Rule **JavaScript is not multi-threaded… but it behaves like it is.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
✨ 𝗪𝗿𝗶𝘁𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝘁𝗿𝗶𝗻𝗴𝘀 𝗟𝗶𝗸𝗲 𝗔 𝗛𝘂𝗺𝗮𝗻 ⤵️ Template Literals in JavaScript: Write Strings Like a Human ⚡ 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/d_HhAEsM 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Why string concatenation becomes messy in real apps ⇢ Template literals — the modern way to write strings ⇢ Embedding variables & expressions using ${} ⇢ Multi-line strings without \n headaches ⇢ Before vs After — readability transformation ⇢ Real-world use cases: HTML, logs, queries, error messages ⇢ Tagged templates (advanced but powerful concept) ⇢ How interpolation works under the hood ⇢ Tradeoffs & common mistakes developers make ⇢ Writing cleaner, more readable JavaScript Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Frontend #Programming #CleanCode #Hashnode
To view or add a comment, sign in
-
Day 11 / 30 - Javascript Coding Challenge - Memoization in JavaScript 🚀 Problem: Given a function fn, return a memoized version of that function. A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value. You can assume there are 3 possible input functions: sum, fib, and factorial. sum accepts two integers a and b and returns a + b. Assume that if a value has already been cached for the arguments (b, a) where a != b, it cannot be used for the arguments (a, b). For example, if the arguments are (3, 2) and (2, 3), two separate calls should be made. fib accepts a single integer n and returns 1 if n <= 1 or fib(n - 1) + fib(n - 2) otherwise. factorial accepts a single integer n and returns 1 if n <= 1 or factorial(n - 1) * n otherwise. Solution: function memoize(fn) { let memoValues = {}; return function (...args) { const key = JSON.stringify(args) if (key in memoValues) { return memoValues[key]; } else { memoValues[key] = fn(...args); return memoValues[key]; } }; } #JavaScript #Memoization #DSA #CodingPractice #100DaysOfCode #FrontendDevelopment
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