JavaScript: The Why And How Of Strict Mode
By this guy:
JavaScript: The Why And How Of Strict Mode + Linting
By this guy:
JavaScript: Serious Business
Spot the bug
// min: return the smallest element in arr
function min(arr) {
var result = Infinity;
for (var i = 0; i < arr.length; i++) {
if (arr[i] < result) {
reuslt = arr[i];
}
}
return result;
}
Spot the bug
// min: return the smallest element in arr
function min(arr) {
var result = Infinity;
for (var i = 0; i < arr.length; i++) {
if (arr[i] < result) {
reuslt = arr[i]; // <== RIGHT HERE
}
}
return result;
}
Without Strict Mode
> min([3,1,2])
Infinity
With Strict Mode
> min([3,1,2])
Uncaught ReferenceError: reuslt is not defined
Strict Mode
- Catches mistakes at runtime
- Throws errors on bad behavior
Let's try one more
var isNodejs = (typeof module) !== 'undefined' &&
(typeof module.exports) !== 'undefined';
if (isNodejs) {
function open(filename) {
return require('fs').readFileSync(filename);
}
}
Without Strict Mode
(In a browser)
> typeof readFile
"function"
> readFile('somefile')
Uncaught ReferenceError: require is not defined
With Strict Mode
Uncaught SyntaxError: In strict mode code,
functions can only be declared at top level or
immediately within another function.
> typeof readFile
"undefined"
Some other things you can't do in strict mode
-
undefined = 123;
-
delete Object.prototype;
-
var obj = { name: 'foo', name: 'bar' };
Strict Mode Comes In
2 Forms
- Script Form
-
'use strict'; var a = 123;
- Function Form
-
function foo() { 'use strict'; return 123; }
Script Form Has One Big Gotcha
- Picture 2 Files
- strict.js
'use strict'; var a = 123;
- non-strict.js
b = 456;
Let's concatentate them
'use strict';
var a = 123;
b = 456;
Let's concatentate them
'use strict';
var a = 123;
b = 456; // <== error in strict mode
Conclusion: Use Function Form
-
(function () { 'use strict'; // a bunch of code window.a = 123; })();
Exception: Unit Tests
- Do you concat your test files?
- No?
- Script Form is OK