Activating JavaScript Strict Mode in Individual Functions

You can also enable string mode for a particular function by adding  ‘use strict’; or “use strict”; at the beginning of the function.

Syntax:

functionfunctionName() {    ‘use strict’;    // function body}// orfunctionfunctionName() {    "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:

functionName() {  // Function without strict mode    name = "Rack"    console.log("Name is: "+ name) // No error here}functionAge() {  // Function with strict mode    "use strict";    age = "22"    console.log("Age is: "+ age) // Error here}Name()Age()

Output:

Name is: RackC:\Users\ag290\OneDrive\Desktop\journalDev-2023\january\strict mode\app.js:8    age = "22"        ^ReferenceError: age is not defined

Also Read:

Leave a Reply

Your email address will not be published. Required fields are marked *

Share this article:

RSS2k
Follow by Email0
Facebook780
Twitter3k
120
29k
130k
error

Please spread the word :)