JavaScript strict mode explained: purpose and functionality

I keep seeing "use strict"; at the beginning of JavaScript files and functions. What exactly does this directive accomplish?

I understand it enables strict mode, but I’m not clear on what changes when you use it. Does it affect how variables are declared? Does it change error handling? Are there performance benefits?

Also wondering about browser support - do all modern browsers recognize this directive? Should I be using it in my current projects?

Here’s a basic example:

function calculateTotal() {
    "use strict";
    let price = 100;
    let tax = 0.08;
    result = price * (1 + tax); // What happens here in strict mode?
    return result;
}

What specific behaviors does strict mode enforce that regular JavaScript doesn’t?

Strict mode significantly alters how JavaScript behaves by enforcing stricter parsing and error handling rules. For instance, in your code example, the line result = price * (1 + tax) would raise a ReferenceError, as strict mode doesn’t allow the assignment to an undeclared variable. Without strict mode, this would have created a global variable, which complicates debugging. Additionally, in strict mode, this is undefined in functions unless explicitly bound, preventing unintended global scope modifications. It also introduces errors for assignments to read-only properties and disallows duplicate parameter names. Modern browsers, including IE10 and above, support strict mode, and using it is advisable for new projects to catch common mistakes early and enhance debugging.

I’ve migrated a bunch of legacy codebases to strict mode, and the biggest change is how it handles silent failures. Your example would throw an error because result isn’t declared, but there are other gotchas that trip up developers. Strict mode won’t let you use reserved words as variable names, and it makes eval() create its own scope instead of messing with the surrounding context. I find it really helpful for preventing accidental overwrites of built-in objects. You can apply strict mode globally or per-function - I’d start with function-level when retrofitting existing code. The performance boost is pretty small, but the debugging advantages are huge, especially in larger apps where tracking down scope issues becomes a nightmare.

yep, that result line will crash cuz u didn’t declare the variable first. strict mode makes js way less forgiving, which is gr8 for catchin bugs early. plus it prevents weird stuff like accidentally creatin global vars.