What does "use strict" do?

use strict is a ES5 feature in JavaScript that makes our code in Strict Mode in functions or entire scripts. Strict Mode helps us avoid bugs early on in our code and adds restrictions to it.

Restrictions that Strict Mode gives us.

  • Assigning or Accessing a variable that is not declared.
function returnY() {
'use strict';
y = 123;
return y;
}
  • Assigning a value to a read-only or non-writable global variable;
'use strict';
var NaN = NaN;
var undefined = undefined;
var Infinity = 'and beyond';
  • Deleting an undeletable property.
'use strict';
const obj = {};
Object.defineProperty(obj, 'x', {
value: '1',
});
delete obj.x;
  • Duplicate parameter names.
'use strict';
function someFunc(a, b, b, c) {}
  • Creating variables with the use of the eval function.
'use strict';
eval('var x = 1;');
console.log(x); //Throws a Reference Error x is not defined
  • The default value of this will be undefined.
'use strict';
function showMeThis() {
return this;
}
showMeThis(); //returns undefined

There are many more restrictions in Strict Mode than these.


October 20, 2022
931