Created
January 18, 2016 16:53
-
-
Save thurt/ca0133dde595b1bb4962 to your computer and use it in GitHub Desktop.
Examples of 'use strict' in the browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script> | |
'use strict' | |
// this 'use strict' only applies within this <script> tag | |
</script> | |
<script> | |
// there is no 'use strict' in this <script> tag | |
// so this assignment does not throw a reference error | |
// a, b, and c are global scope | |
var a = b = c = 1 | |
console.log(`a=${a}, b=${b}, c=${c}`) | |
</script> | |
<script> | |
'use strict' | |
// throws a reference error for f | |
// d can be dereferenced but it is undefined | |
// e cannot be dereferenced -- if you try it will throw a ref error | |
// f cannot be dereferenced -- if you try it will throw a ref error | |
try { | |
var d = e = f = 1 | |
} catch (error) { | |
console.log(`ERROR: ${error.message}`) | |
console.log(`d=${d} -- cannot deref e or f without another error`) | |
} | |
</script> | |
<script> | |
'use strict' | |
// this 'use strict' applies to any function in the same <script> tag | |
function try_this() { | |
var g = h = i = 1 // same behavior as last example | |
} | |
try_this() // execution stops here since error was thrown | |
console.log('Never gets called') | |
</script> | |
<script> | |
'use strict' // 'use strict' also applies to IIFEs | |
;(function () { | |
var j = k = l = 1 // same behavior as last example | |
console.log(`j=${j}, k=${k}, l=${l}`) | |
})() | |
console.log('Never gets called') | |
</script> | |
<script> | |
function strict_func() { | |
'use strict' // scoped only to this function | |
} | |
function non_strict_func() { | |
var m = n = o = 1 // this assignment is not affected by 'use strict' | |
console.log(`m=${m}, n=${n}, o=${o}`) | |
} | |
strict_func() | |
non_strict_func() | |
</script> | |
</head> | |
<body> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment