What is 'use strict' in JavaScript for?
Answer
"use strict"
is a directive in JavaScript that enables strict mode, a stricter set of rules for writing JavaScript code. It helps catch potential bugs, enforces safer coding practices, and improves performance in some cases.
How to Use "use strict"
Globally
Placed at the top of a script file, it applies strict mode to the entire file.
'use strict';
x = 10; // Error: x is not defined
Function Scope
Placed at the beginning of a function, it applies strict mode only within that function.
function myFunction() {
'use strict';
y = 20; // Error: y is not defined
}
myFunction();
Key Features and Benefits of Strict Mode
- Prevents the Use of Undeclared Variables
'use strict';
a = 10; // Error: a is not defined
- Disallows Duplicating Parameter Names
'use strict';
function example(a, a) {} // Error: Duplicate parameter name
- Eliminates Silent Errors
Some operations that fail silently in non-strict mode throw errors in strict mode.
'use strict';
delete Object.prototype; // Error: Cannot delete property
- Prevents
this
from Defaulting towindow
In functions, this
defaults to undefined
instead of the global object.
'use strict';
function example() {
console.log(this); // undefined
}
example();
- Makes Code Easier to Optimize
Some optimizations are easier for JavaScript engines to perform in strict mode.
- Reserved Keywords for Future
Disallows the use of keywords like implements
, interface
, and private
, ensuring compatibility with future JavaScript versions.
When to Use "use strict"
- When you want cleaner, more predictable code.
- When debugging or developing large applications to catch potential issues early.
- As a good practice in modern JavaScript development.