Strict mode permits you from writing a function or program in a strict operating context. This context throws different exceptions and block specific actions from being taken. The 'use strict';
statement guides the browser to use the Strict mode, which is a diminished and more secure list of JavaScript features.
You can apply strict mode in the follow two ways:
In
You can apply strict mode for the entire script by writing 'use strict';
before any other statements:
// Entire Script Strict mode
'use strict';
let testString = "In Strict Mode.";
If you try to concatenate strict mode script with a Non-strict script, it will look entirely Strict, but it can be Non-strict. In the same way, you can concatenate a Non-strict script with Strict script and, although it will look entirely Non-strict, it can cause confusion. You can concatenate the same type of scripts without any issue, but in the concatenation of Strict and Non-strict scripts, use of Strict mode based on function-by-function is recommended.
You can apply it to individual function by writing 'use strict';
in function’s body before any other statement as below:
function testFunction() {
// Strict Mode in Function
'use strict';
return "strict mode test function!";
}
If we mistype the variable’s name, JavaScript usually creates a new global variable. However, this is impossible in Strict mode:
'use strict';testVar = 28;// You will face an error because variable is not declared.// You can verify it by clicking on Run button.
This error occurs when you are unable to delete a variable, an object, or a function in Strict mode. This is shown below:
'use strict';function testFun(num, age) {};delete testFun;// You will face an error.// You can verify it by clicking on Run button.
Strict mode does not allow you to duplicate a parameter name in JavaScript. This is shown below:
'use strict';function testFun(age, age) {};// You will face an error.// You can verify it by clicking on Run button.
You are unable to execute some properties in Strict mode, e.g., you cannot set the get-only
property.
'use strict';let testObj = {get age() {return 0} };testObj.age = 28;// You will face an error.
You cannot use some string functions in Strict mode. For example, the eval
function.
'use strict';let eval = 9.33;// You will face an error.// You can verify it by clicking on Run button.
Free Resources