Strict Mode in JavaScript
Strict mode in JavaScript is a special operating mode that helps write safer and better quality code. By enabling it, you activate additional checks and restrictions that prevent common errors.
What Does Strict Mode Change?
- Prohibits using undeclared variables.
"use strict";
x = 10; // Error: variable not declared
- Prohibits deleting variables, functions or objects.
"use strict";
delete x; // Error: cannot delete variable or function
- Restricts
thisin functions. Without strict mode:
function showThis() {
console.log(this); // `this` refers to global object (window in browser)
}
With strict mode:
"use strict";
function showThis() {
console.log(this); // `this` will be undefined
}
- Prevents using reserved words.
Words like
implements,interface,packagecannot be used as variables or function names.