JavaScript Typing Coercion Explained

JavaScript isn’t confusing. 𝗦𝗸𝗶𝗽𝗽𝗶𝗻𝗴 𝘁𝗵𝗲 𝗳𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀 𝗶𝘀. 😉 Today I learned something interesting about 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝘁𝘆𝗽𝗲 𝗰𝗼𝗲𝗿𝗰𝗶𝗼𝗻, and it finally made this make sense 👇 2 + 2 → 4 "2" + "2" → "22" 2 + 2 - 2 → 2 "2" + "2" - "2" → 20 At first glance, the last line looks wrong. But JavaScript is actually being very logical. Here’s what I learned 👇 🔹 + 𝗯𝗲𝗵𝗮𝘃𝗲𝘀 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁𝗹𝘆 If 𝗮𝗻𝘆 𝗼𝗽𝗲𝗿𝗮𝗻𝗱 𝗶𝘀 𝗮 𝘀𝘁𝗿𝗶𝗻𝗴, + performs 𝘀𝘁𝗿𝗶𝗻𝗴 𝗰𝗼𝗻𝗰𝗮𝘁𝗲𝗻𝗮𝘁𝗶𝗼𝗻, not math. "2" + "2" → "22" 🔹 - 𝗱𝗼𝗲𝘀 𝗡𝗢𝗧 𝘄𝗼𝗿𝗸 𝘄𝗶𝘁𝗵 𝘀𝘁𝗿𝗶𝗻𝗴𝘀 When JavaScript sees -, it 𝗳𝗼𝗿𝗰𝗲𝘀 𝗻𝘂𝗺𝗲𝗿𝗶𝗰 𝗰𝗼𝗻𝘃𝗲𝗿𝘀𝗶𝗼𝗻. "22" - "2" → 22 - 2 → 20 💡 This behavior is called 𝘁𝘆𝗽𝗲 𝗰𝗼𝗲𝗿𝗰𝗶𝗼𝗻. Once the basics are clear, JavaScript stops being “weird” and starts making sense 🚀 #JavaScript #WebDevelopment #LearningInPublic #Programming #Coding #Fundamentals

  • No alternative text description for this image

I don't understand for last because everything is string but output is "integer" 🤔

Like
Reply

Aaiswarya PM, Do not adopt that approach; instead, follow a proper coding practice: explicitly coerce (cast) data types. Avoid mixing data types under all circumstances.

See more comments

To view or add a comment, sign in

Explore content categories