“use strict” What does this mean in Javascript

In this blog post we are going learn about “use strict“; and it use in javascript.

“use strict”; helps to run our javascript in Strict Mode. It is new feature in ECMAScript 5 that allows us to place a program, or a function, in a “strict” operating context. This strict context prevents certain actions from being taken and throws more exceptions. It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.

It’s time to start using JavaScript strict mode

Strict mode helps out in a couple of ways:
> Strict mode changes previously accepted “bad syntax” into real errors
> Throws errors, when relatively “unsafe” actions are taken (Such as gaining access to the global object)
> It disables features that are confusing or poorly thought out
> Strict mode makes it easier to write “secure” JavaScript

“use strict”; //global scope (all code will execute in strict mode).
pi = 3.14; // This will cause an error
myFunction(); // This will also cause an error

function myFunction() {
x = 3.14;
}

The above code, if we run in any latest browsers which supports strict mode. It will throws exception saying “ReferenceError: assignment to undeclared variable pi”.

we can use strict file level(global) or function level. Here is code sample for it

// Non-strict code…
(function(){
“use strict”;
// Define your library strictly…
})();
// Non-strict code…

What not allowed in Strict Mode

  • A variable (property or object) without declaring it (Eg:- pi =3.14)
  • Deleting a variable, a function, or an argument (Eg:- delete pi) Hint: applying the ‘delete’ operator to an unqualified name is deprecated
  • Defining a property more than once (Eg:- var website = {url:”https://shareourideas.com”,site:”Share our Ideas”,url:”https://shareourideas.com”)
  • Duplicating a parameter name in function (Eg:- function getName(id,id))
  • Writing to a read-only property (Eg:- var obj = {}; obj.defineProperty(obj, “pi”, {value:0, writable:false}); obj.pi = 3.14;)
  • Future reserved keywords are not allowed (like implements, interface, package, private, protected, public, static and field)
  • and more please refer below links

Strict mode is supported in:
IE 10, FF 4, GC 13, Safari 5.1 & Opera 12.

Reference links:

http://www.w3schools.com/js/js_strict.asp

http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode

https://msdn.microsoft.com/library/br230269%28v=vs.94%29.aspx

 

Leave a Reply