JavaScript Semicolon Insertion Gotcha: Avoid Silent Bugs

💡 Think semicolons don’t matter in JavaScript? Think again. Here’s a subtle but powerful concept: Automatic Semicolon Insertion (ASI). At first glance, this code looks perfectly fine: const arr = [1, 2, 3] (function () { console.log("Hello 👋") })() But instead of printing "Hello 👋", it throws: ❌ TypeError: arr is not a function 👉 Why? JavaScript doesn’t automatically insert a semicolon after the array declaration. So it interprets the code like this: const arr = [1, 2, 3](function () { ... })() Now it tries to call arr as a function — and arrays aren’t callable. ✅ The Fix is simple: const arr = [1, 2, 3]; (function () { console.log("Hello 👋") })() Now everything works as expected. 🔍 Key Takeaways: • JavaScript uses ASI, but it’s not always reliable • Starting a line with (, [, or + can cause unexpected behavior • Missing semicolons can silently change how your code is interpreted • Always be explicit when your next line starts with an IIFE or expression 🚀 Pro Tip: Even if you prefer a “no-semicolon” style, make sure to add one before IIFEs or tricky expressions to avoid bugs that are hard to debug. ⚡ JavaScript isn’t just about writing code — it’s about understanding how the engine reads your code. #JavaScript #WebDevelopment #CodingTips #Frontend #Programming #CleanCode

  • text

To view or add a comment, sign in

Explore content categories