Ads

Javascript 2 - "use strict" in JavaScript programming is really necessary?


Strict Mode is a new feature in ECMAScript 5.


It's just a string you put in your JavaScript files (either at the top of your file or inside of a function) that looks like this:


"use strict";


This statement instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript.



Strict mode can be used as a warning reminder when you are doing something wrong or unwanted with your code.


When a JavaScript engine sees this directive, it will start to interpret the code in a special mode. In this mode, errors are thrown up when certain coding practices that could end up being potential bugs are detected.


Hers is the simple demonstration:


<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
    <script>
      function IamFree () {
        if (this) {
          alert('value of this is '+this)
        }
      }

      function IamStrict () {
        'use strict'
        if (this) {
          alert('I am Strict')
        }
        else{
            alert('value of this is '+this)
        }
      }

      IamFree()
      IamStrict()
    </script>
  </head>
  <body></body>
</html>


In IamFree() function 'this' value is false, since 'this' refers to global object and '!this' becomes true 


function IamFree () {
	if (this) {
	  alert('value of this is '+this)
	}
} 


But in IamStrict() function 'this' value is set to true, since in strict mode the keyword 'this' does not refer to global object, unlike traditional JS. So here, 'this' is 'undefined' and '!this' becomes false.


function IamStrict () {
	'use strict'
	if (this) {
	  alert('I am Strict')
	}
	else{
		alert('value of this is '+this)
	}
}


Can we use strict mode in React JS?


Yes! why not. we can use strict mode in react js. below is the sample code


function IamStrict()
{
    return(
        <React.StrictMode>
            <div>I am inside strict mode</div>
        </React.StrictMode>
    )
}


Conclusion:

  • Strict Mode is a tool for highlighting potential problems in an application.
  • Warning about legacy string ref API usage
  • Warning about deprecated findDOMNode usage
  • Detecting legacy context API
  • Strict mode checks are run in development mode only; they do not impact the production build.


That's it for this article.


See you in next article, take care bye


Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !