You can also enable string mode for a particular function by adding ‘use strict’; or “use strict”; at the beginning of the function.
Syntax:
function functionName() { ‘use strict’; // function body } // or function functionName() { "use strict" ; // function body } |
This statement should be the first statement of the function excluding comments.
Adding ‘use strict’; or “use strict”; at the beginning of a function has a local scope which means all the code in that script is executed usually and the code inside the function will only execute in strict mode.
Example:
function Name() { // Function without strict mode name = "Rack" console.log( "Name is: " + name) // No error here } function Age() { // Function with strict mode "use strict" ; age = "22" console.log( "Age is: " + age) // Error here } Name() Age() |
Output:
Name is: Rack C:\Users\ag290\OneDrive\Desktop\journalDev-2023\january\strict mode\app.js:8 age = "22" ^ ReferenceError: age is not defined |
74