JavaScript use strict is a string you write at the top of a script file or function to run your code in strict mode.
"use strict"
You can then catch errors that would lead to lengthy debugging sessions.
Although many things can lead to such errors, they mainly result from ignoring scope and hoisting rules. Let's learn the concepts before using JavaScript use strict practically.
Understanding basic concepts
Scope
A scope, also called context, defines where a variable is effective. There are four main types of scopes in JavaScript. These are:
- global:Â A variable in global scope is usable across script files, functions, and other code blocks.
- module :Â A module is a file with code. A variable in a module is only effective in that module unless explicitly exported to other modules.
- function: A variable created inside a function is effective inside the function, and your code throws an error if you attempt to use the variable outside the function. Related to function scopes are block scopes.
- block:Â A block is code enclosed in curly braces
{}
. You create a block with functions, if/else control flows, or loops. However, sometimes your code may disobey scoping rules when hoisting occurs. But what is hoisting?
Hoisting
Hoisting is when your variable or function is initialized on your behalf. So, you can use the variable or function before defining it.
Here is the thing.
JavaScript mainly reads your code from top to bottom of the page before running it. If it comes across variables defined with the var
keyword or regular functions, it initializes it at the top of the page.
And that comes with many undesirable effects. For example, an undefined variable can be initialized, making it appear as if you had defined it before using it. That contradicts the expectation that a variable should be defined with the var
, let
, or const
keywords.
Worse yet, duplicating function parameters can result in undesirable effects.
Although let
and const
keywords and arrow functions prevent hoisting and scope-related errors, sometimes the errors slip into production. That is why you may need to apply JavaScript use strict, as shown below.
Typical errors to solve with JavaScript use strict
Example-1: Using undeclared variables
JavaScript use strict prevents you from applying a variable before defining it.
Here is an example using a number, a string, and an object.
Without JavaScript use strict
Input
str = "String"
num = 639
obj = { str:"String", num:639 }
console.log(str)
console.log(num)
console.log(obj)
console.log(obj['num'])
Output
String
639
{ str: 'String', num: 639 }
639
With JavaScript use strict
Input
"use strict"
str = "String"
num = 639
obj = { str:"String", num:639 }
console.log(str)
console.log(num)
console.log(obj)
console.log(obj['num'])
Output
/home/user/GoLinuxCloud/useStrict/main.js:3
str = "String"
^
ReferenceError: str is not defined
at Object.<anonymous> (/home/user/GoLinuxCloud/useStrict/main.js:3:5)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.12.0
The code throws an exception after catching the first error.
Example-2: Using octal instead of decimal numbers
You can enter the strict mode to prevent you from using octal (instead of decimal) numbers and getting undesirable output. Assume you want to store integer seventy-two and apply it later. You accidentally prepend the value with a zero. That converts the number to an octal number.
Without JavaScript use strict
Input
const seventyTwo = 072
console.log(seventyTwo)
Output
58
You get the octal value of 072 = 7(8^1) + 2(8^0) = 58.Â
With JavaScript use strict
Input
"use strict"
const seventyTwo = 072
console.log(seventyTwo)
Output
/home/user/GoLinuxCloud/useStrict/main.js:3
const seventyTwo = 072
^^^
SyntaxError: Octal literals are not allowed in strict mode.
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1088:15)
at Module._compile (node:internal/modules/cjs/loader:1123:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.12.0
Now you get an output telling the origin of the previous error.
Example-3: Deleting a variable the wrong way
You may attempt to remove a primitive, function, or undeletable object property using the delete
keyword.Â
Without JavaScript use strict
Input
// primitive
const num = 639
delete num
// function
const addTwoNums = (num1, num2) => num1 + num2
delete addTwoNums
// undeletable property
delete Object.prototype
Output
You neither get a (success) message nor an error.
With JavaScript use strict
Input
"use strict"
// primitive
const num = 639
delete num
// function
const addTwoNums = (num1, num2) => num1 + num2
delete addTwoNums
// undeletable property
delete Object.prototype
Output
/home/user/GoLinuxCloud/useStrict/main.js:5
delete num
^^^
SyntaxError: Delete of an unqualified identifier in strict mode.
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1088:15)
at Module._compile (node:internal/modules/cjs/loader:1123:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.12.0
Now you get a syntax error:Â Delete of an unqualified identifier in strict mode.
Example-4: Duplicating a parameter name
By entering the strict mode, you can prevent errors resulting from duplicating a function parameter's name.Â
Assume you want a function to return the sum of two numbers. You accidentally supply the function with a duplicate parameter name.
Without JavaScript use strict
Input
function addTwoNums(num, num) {
return num + num
}
const sevenPlusNine = addTwoNums(9, 7)
console.log(sevenPlusNine)
Output
14
Instead of (9 + 7 = ) 16, you get (7 + 7 = ) 14.Â
With JavaScript use strict
Input
"use strict"
function addTwoNums(num, num) {
return num + num
}
const sevenPlusNine = addTwoNums(9, 7)
console.log(sevenPlusNine)
Output
home/user/GoLinuxCloud/useStrict/main.js:3
function addTwoNums(num, num) {
^^^
SyntaxError: Duplicate parameter name not allowed in this context
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1088:15)
at Module._compile (node:internal/modules/cjs/loader:1123:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.12.0
The strict mode prevents you from duplicating the num
parameter.Â
Additionally, you could avoid the error by using an arrow function instead of entering the strict mode.
const addTwoNums = (num, num) => num + num
const sevenPlusNine = addTwoNums(7, 9)
console.log(sevenPlusNine)
Example-5: Using reserved or deprecated keywords
It is advisable to avoid declaring variables with preserved keywords or using deprecated functions even if your code does not throw an error. You can enter the strict mode to prevent you from using functions like eval
and preserved keywords like package
, protected
, public
, let
, static
, and yield
.
Without JavaScript use strict
Input
const private = 47
console.log(private)
Output
47
With JavaScript use strict
Input
"use strict"
const private = 47
console.log(private)
Output
/home/user/GoLinuxCloud/useStrict/main.js:3
const private = 47
^^^^^^^
SyntaxError: Unexpected strict mode reserved word
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1088:15)
at Module._compile (node:internal/modules/cjs/loader:1123:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.12.0
The strict mode prevents you from using the preserved private
access modifier keyword.
Key takeaways
JavaScript use strict
- should be placed at the topmost part of a script file or function
- helps you catch syntax and reference errors.Â