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

Paulo Henrique Ferreira
2 min readJan 15, 2023

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:

  1. Variables must be declared before they are used;
  2. Variables and functions need to have different names;
  3. All properties of an object need to have different names;
  4. Can’t delete variables, functions, and objects and their properties with the keyword delete;
  5. Can’t use keywords eval and arguments;

To illustrate:

  1. 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.

References

  1. https://www.geeksforgeeks.org/strict-mode-javascript/
  2. https://www.w3schools.com/js/js_strict.asp

--

--

Paulo Henrique Ferreira

Software Developer, Bodybuilder and passionate about knowledge.