Javascript's Slightly Stricter Mode
A confession
I am not really a Javascript developer
Goodfilms
Coffeescript
When did I start using it?
"use strict";
Yeoman generated it for me.
This talk is now:
Glen didn't know about Javascript
mildly interesting
strict mode
Bugs
Strict mode fixes
didn't know existed
# rubby.rb
a = "foo"
# cahfee.coffee
a = "foo"
//lolscript.js
var a = "foo";
var a = Math.PI;
console.log(a);
// 3.14159...
var a = Math.PI
console.log(a)
// 3.14159...
a = Math.PI
console.log(a)
// 3.14159...
function someSetup() {
a = Math.PI;
}
someSetup();
console.log(a);
// 3.14159...
Non-strict mode | Strict mode |
|
|
throws ReferenceError"Strict mode forbids implicit creation of global property 'a'" |
Non-strict modeYOLO mode | Strict mode |
|
|
throws ReferenceError"Can't find variable: a" |
removes some lols
makes code faster
changes important stuff
YOLO mode
var eval, arguments;
eval = 010;
delete eval;
arguments = {x: 1, x: eval}
function y(a, a) {
return a;
}
console.log(y(null, arguments.x));
// 8
Strict mode
"use strict";
var eval, arguments; // keywords as vars BOOM
eval = 010; // octals BOOM
delete eval; // deleting locals BOOM
arguments = {x: 1, x: eval} // duplicate key BOOM
function y(a, a) { // duplicate argument BOOM
return a;
}
Syntax Error
"Parse error"Stop the lols!
Performance?
YOLO mode | Strict mode |
|
|
Syntax Error"Parse error" |
YOLO mode | Strict mode |
|
|
Note: Function.caller can do most of the same things anyway | Type Error"Unable to access callee of strict mode function" |
Serious time
Semantic changes
Implicit global this
|
|
this becomes window | this becomes undefined |
|
|
Strict Mode invocation | Strict Mode declaration |
Evals | |
|
|
Eval'd code getting all | Eval'd code evaluated |
Javascript code
was written YOLO
break if interpreted as strict.
Strict Mode is ignored
older browsers
Be safe
Concatenation | |
|
|
Other code interpreted | Your code is |
|
|
Your code strict ✔ | Other code unchanged ✔ |
Wrap every file
// safe.js
(function() {
"use strict";
// go bananas.
})();