Return vs Throw in JavaScript Error Handling

🚀 Day 3 of #30DaysOfJavaScript — this changed how I think about errors 👇 While solving To Be Or Not To Be on LeetCode, I got stuck on a simple thought: 👉 “Why can’t I just return { error: "Not Equal" }?” It felt logical. Return an error → problem solved… right? ❌ Wrong. The test cases were still failing. That’s when I discovered the real difference: 💥 Returning an error is NOT the same as throwing an error. return { error: "Not Equal" }; // normal flow throw new Error("Not Equal"); // stops execution 💡 Key insight: return → continues execution silently throw → immediately stops execution and signals failure And that’s exactly what the problem expects. 👉 This is how real systems work: APIs throw errors for invalid requests Backend validations reject bad data Bugs don’t get silently ignored Small problem, but a big mindset shift. Curious — when do you prefer return vs throw in your code? 👇 #JavaScript #LeetCode #ErrorHandling #CodingJourney #Developers #LearnInPublic

  • text

To view or add a comment, sign in

Explore content categories