Strict Mode in Javascript
Strict mode is a feature in JavaScript that allows you to opt into a stricter set of rules for writing code. When strict mode is enabled, certain actions that would otherwise be allowed in JavaScript are either disallowed or cause errors, making it easier to write code that is more reliable and easier to maintain.
To enable strict mode in JavaScript, you simply add the following string at the top of your script or function:
'use strict';
Once strict mode is enabled, the following changes are made to the way JavaScript code is executed:
- Assigning a value to an undeclared variable or property throws a ReferenceError.
- Deleting a variable, function, or argument throws a SyntaxError.
- Assigning a value to a read-only property throws a TypeError.
- Defining a function in a block statement (e.g. inside an if statement) throws a SyntaxError.
- The with statement is not allowed, and using it throws a SyntaxError.
- Duplicates in object property names or function parameter names cause a SyntaxError.
- The
eval()
function creates a new scope, and declaring a variable or function in aneval()
statement does not create that variable or function in the current scope.
These are just some of the changes that occur when strict mode is enabled in JavaScript. There are many others, and you can find a complete list in the MDN Web Docs.
Overall, strict
mode is a useful feature in JavaScript that can help you write better code by catching errors and enforcing stricter rules. It is recommended that you use strict mode in all of your JavaScript code to help ensure that it is as reliable and maintainable as possible.
Here's an example of how to use strict mode in JavaScript:
'use strict';
// This code is in strict mode
let myVariable = 42;
console.log(myVariable);
function myFunction() {
// This code is in strict mode
let myOtherVariable = 23;
console.log(myOtherVariable);
}
myVar = "hello World"; // Error
myFunction();
In this example, we have enabled strict mode by adding the string use strict;
at the beginning of the script. We then define a variable myVariable and a function myFunction(), both of which are in strict mode.
We then call myFunction(), which logs the value of a local variable myOtherVariable to the console. Because this code is also in strict mode, any errors that might occur (such as assigning a value to an undeclared variable) will cause a runtime error.
By using strict mode in your JavaScript code, you can catch these errors and prevent them from causing unexpected behavior or crashes in your application. It's a good practice to use strict mode in all of your JavaScript code to help ensure that it is as reliable and maintainable as possible.