While reading about strict mode on MDN I really was surprised to read the follow
ID: 647353 • Letter: W
Question
While reading about strict mode on MDN I really was surprised to read the following near the end of the page, quote:
Browsers don't reliably implement strict mode yet, so don't blindly depend on it. Strict mode changes semantics. Relying on those changes will cause mistakes and errors in browsers which don't implement strict mode. Exercise caution in using strict mode, and back up reliance on strict mode with feature tests that check whether relevant parts of strict mode are implemented. Finally, make sure to test your code in browsers that do and don't support strict mode. If you test only in browsers that don't support strict mode, you're very likely to have problems in browsers that do, and vice versa.
As far as I understand it, strict mode is a redused set of "nonstict" mode, thus I can't imagine situation where strict code can't run correctly in a nonstrict browser. So, the question is this statement really makes sense? Is the any situation where strict to "nonstrict" switch will make code invalid?
Explanation / Answer
Strict mode isn't just reduced functionality from "non-strict" mode. There's also some altered functionality. Say we'd like to write the following ES6 code:
function callOnObjectWithArgs(fn, obj, ...args) {
fn.apply(obj, args);
}
But since browsers haven't implemented the rest operator (...) yet, we could do something like this in strict mode:
function callOnObjectWithArgs(fn, obj) {
"use strict";
var splice = Array.prototype.splice;
splice.call(arguments, 0, 2); // Remove the first 2 elements (fn & obj)
fn.apply(obj, arguments);
}
callOnObjectWithArgs(console.log, console, 1, 2, 3); // -> 1 2 3
However, this code would not work in "non-strict" mode.
// Using callOnObjectWithArgs without the "strict mode"; invocation
callOnObjectWithArgs(console.log, console, 1, 2, 3) // -> TypeError: undefined is not a function
This is because by removing the first two elements from the arguments object, fn and obj will no longer point to the first two parameters passed to the function, but instead would then point to what was arguments[2] and arguments[3] from before the first two elements were removed (1 and 2). This is because in "non-strict" mode, named function parameters always point to the corresponding indices in the arguments object, whereas named parameters in strict mode are not bound to the arguments object in any way.
This is why you should always write code that is compatible with both strict and regular mode.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.