JavaScript this binding in strict mode

🧠 JavaScript Question: Why does this become undefined in strict mode? While revisiting some JavaScript fundamentals, I came across an interesting behavior related to default this binding. Consider this code: "use strict"; function showUser() { console.log(this); } showUser(); Output: undefined But remove "use strict" and run it again: function showUser() { console.log(this); } showUser(); Output: window So why does this happen? ⚙️ The Reason In JavaScript, the value of this depends on how a function is called, not where it is defined. If a function is called without an object, JavaScript applies default binding. But historically this created a serious problem. 📜 The ES3 Problem Before ECMAScript 5, calling a constructor without new would silently modify the global object. function User(name) { this.name = name; } User("John"); // forgot 'new' console.log(window.name); Output: John This accidentally polluted the global object, which could break applications. 🚨 The ES5 Fix — Strict Mode To prevent this, strict mode changed the default behaviour. Default binding now becomes: Non-strict mode → this = window Strict mode → this = undefined Now if we forget new, JavaScript throws an error instead of silently modifying globals. ✅ Takeaway Strict mode was introduced to make JavaScript safer and less error-prone, especially for mistakes like calling constructors without new. Understanding these small design decisions helps us appreciate how JavaScript evolved from ES3 to modern standards. #javascript #frontenddevelopment #webdevelopment #softwareengineering #ecmascript

To view or add a comment, sign in

Explore content categories