Saturday 9 April 2016

The strict mode in javascript

//strict mode in js
var actNow = function(){
 'use strict';
    newVariable = 9;
};
actNow();/* Uncaught ReferenceError: newVariable is not defined. */
/* Due to strict mode we have to define the variable newVariable with keyword var as the strict mode will not allow us to place the variable in the global scope. */
/* If you use 'use strict' mode in the global space while using thir party libraries you may face problems if the those libraries are not meant to be used in the strict mode. */

//*******************************************************
var actNow = function(){
 //'use strict';
    newVariable = 9;
};
actNow();
/* Here we have commented the line with the strict mode so we get no error from this snippet and the variable will be placed in the global space. */

//*******************************************************
//The 'delete' operator removes a variable from the context
var actNow = function(){
 var newVar = 9;
    delete newVar;
};
actNow();//No error and the code works.
//*******************************************************
//The 'delete' operator is not allowed in the strict mode.
var actNow = function(){
 'use strict';
 var newVar = 9;
    delete newVar;
};
actNow();/* Uncaught SyntaxError: Delete of an unqualified identifier in strict mode. */
/* If we declare a variable in strict mode, we can't get rid of it. */
//*******************************************************
/* The following code gives no error as we are not in strict mode inspite of the fact that both the arguments have the same name.
*/
var actNow = function(){
    var fn = function(x, x){
     //Do something here.
    };
};
actNow();//no error

//*******************************************************
var actNow = function(){
 'use strict'
    var fn = function(x, x){
     //Do something here.
    };
};
actNow();
/* Uncaught SyntaxError: Duplicate parameter name not allowed in this context */
//*******************************************************
'use strict';
var obj ={};
with(obj){
 console.log('using with statement');
};
//*******************************************************

No comments:

Post a Comment