Should 'use strict' Be Used Everywhere in JavaScript?
Basically, 'use strict'; makes code more consistent and less error prone. You can read about the exact details here.
So should it be used everywhere? Contrary to most sources on the internet, the answer is no. For new projects and completely new code it should be used by default, but applying it to old code can in some rare cases cause that code to work differently. For example, here is some code made in an old JS style without 'use strict':
function addMessage(message) { var self = this || {}; self.messages = self.messages || []; self.messages.push(message); } addMessage('message1'); console.log(window.messages); // ["A message"]
The above occurs because the this value refers to the global scope in non-strict code. With adding 'use strict';:
'use strict'; function addMessage(message) { var self = this || {}; self.messages = self.messages || []; self.messages.push(message); } addMessage('message2'); console.log(window.messages); // undefined
Now this does not automatically set to the global scope in that function. Also, notice how no errors occured. In this case, unit testing that old code first before adding 'use strict'; would have caught this error. Though in some cases even unit testing may not be enough, so it is also necessary to manually analyze if old code will act differently under strict mode. Here is a good source on how to do that.
The good news, is in the future most code will automatically be in strict mode either via tools or by using new language features. For example, the upcoming language feature ES6 Modules will be supported natively in browsers and those modules are automatically in strict mode. Note these modules are different from the Node.js modules (there was no universal module format when Node.js was created). So Node.js code is not automatically in strict mode unless a compiler flag is used.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/strict.js

















