"use strict" in JavaScript

What is strict mode

JavaScript's strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally


Strict mode makes several changes to normal JavaScript semantics:

  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.
  3. Prohibits some syntax likely to be defined in future versions of ECMAScript.
     

Syntax 

 

(function(){
  "use strict";
   
  // do you code
})();

 

invoking strict mode

Simply write "use strict" this at the top of a program to enable it for the whole script. You can also use it with in a function like the following 

function strictModeMethod( someVariable ){
   "use strict";
   
   someVariable = 1;
   
   console.log( someVariable);          // 1
   console.log( arguments[0] );        // here
}

strictModeMethod("here")

 

List of features and reasoning 

  1.  Does not allow global variables. it through error if you try use variable with its type declaration  
    someVariable = "test" // error
  2. Silent failing assignments will throw error in strict mode
    NaN = 5;  // error
  3. through an error if you try to delete a non delete able object 
 function test2(arg) {
 	"use strict";
 	
    delete arg; // throughs an error
}

       4. Defining a property more than once in an object literal will cause an exception to be throw an    

        { foo: true, foo: false }  // error

       5. functions parameter names must be unique 

      fun(x,x)  // error

      6. Strict mode does not alias properties of the arguments object with the formal parameter

(function(test){
  "use strict";
   test = 56
   
   
  console.log (test);   // 56
  console.log(arguments[0])   // test ouyput 
})();

      7. arguments.callee does not suppoerted by strict mode.

 

 


Tags:

Share:

Related posts