When you use the "use strict" directive in JavaScript, a strict mode is enabled, ensuring that you comply with stricter rules and handle errors better. Activating strict mode prevents or flags certain JavaScript behaviors that are deemed problematic or error-prone.
'use strict';
// Your code here
Using the "use strict" directive at the top of your JavaScript file or script tag will activate strict mode in your script.
str = 'abc';
console.log(str); // abc
'use strict';
str = 'abc';
console.log(str); ReferenceError: str is not defined
function myFunction() {
"use strict";
// Your code here
}
Here, strict mode is only active within the myFunction function. By doing this, you can apply strict mode selectively to specific functions, even if the rest of the script is not.
function outerFunction() {
// Non-strict mode
function innerFunction() {
"use strict";
// Strict mode enabled for this function
// Your code here
}
// Non-strict mode
// Your code here
}
As shown in this example, strict mode applies only to the innerFunction, while outerFunctions and any other code outside must not be affected.