What is the “use strict” and how to use it to code better with JavaScript
A little tip to improve our project quality and security
If you are coding with JS you must have seen some projects using “use strict”, normally in the first line of the script.
This “use strict” is a literal expression introduced by EcmaScript 5 (2009) to use a specific variant of JS that some syntax or behavior, that by default would be ignored, is treated as a runtime error.
The main restrictions applied by strict mode are:
- Variables must be declared before they are used;
- Variables and functions need to have different names;
- All properties of an object need to have different names;
- Can’t delete variables, functions, and objects and their properties with the keyword delete;
- Can’t use keywords eval and arguments;
To illustrate:
- Using some variable or object without declaring: This code below assigns a value “James Bond” to the variable userName that was not declared before. With strict mode this code will return a ReferenceError:
<html>
<body>
<script>
"use strict"
userName = "James Bond"
</script>
</body>
</html>
2. Deleting parameters, variables, or functions: with the strict mode, this code will return a SyntaxError:
<html>
<body>
<script>
"use strict";
function printMessage() {
console.log("Heeeeeeellow!")
}
printMessage()
delete printMessage
</script>
</body>
</html>
3. The keywords eval and arguments are forbidden: with the strict mode, this code will return a SyntaxError:
<html>
<body>
<script>
"use strict"
let eval = "anything"
</script>
</body>
</html>
Conclusion
Strict mode helps catch a lot of errors at runtime and that’s nice because it prevents certain unexpected behavior from reaching our customers, in addition to preventing malicious actions from being executed to modify properties and objects of our projects through the use of executions via eval, for example.