Search This Blog

2019/11/22

use strict in javascript

"use strict" is introduced in ES5.By Default javascript ignore certain mistakes of coding.enabling strict mode help us prevent errors at time of coding only that cannot be caught otherwise.

one can write "use strict" at beginning of javascript file or at start of function definition as below

    function Add(a,b)
    {
     "use strict"
     return a+b;
    }


common mistakes that get caught with strict mode

1) polluting global namespace
    "use strict"
    function myFunc()
    {
        x=10;//variable x get defined in global namespace
    }

    myFunc()
    console.log(x);

    in function myFunc variable x is assigned value before defining it.so x get defined in global namespace so console.log after myFunc() print 10.

2) Unexpected eval or arguments in strict mode

    "use strict"
    var eval = 3.14;
    console.log(eval);

    var arguments = 3.14;
    console.log(arguments);

3) Delete of an unqualified identifier in strict mode

    "use strict";
    //Delete of an unqualified identifier in strict mode
    var obj={
        x:10,
        y:20
    }

    delete obj;

    console.log(JSON.stringify(obj));

4) readonly property

    "use strict";
    var obj ={
        x:10
    }

    Object.defineProperty(obj,"x",{writable:false});

    obj.x =20;

    console.log(obj.x);

    'obj' has property 'x' which is readonly so we cant assign value to it,by default javascript ignore assignment of value to such property.

5) promotion of this to global namespace

    "use strict";
    function myFunc() {
        console.log(this);
    }
    myFunc();

    if not in strict mode this get promoted to global scope  otherwise this becomes undefined.
     contrary to  normal function arrow function behavior is different for

let func = ()=>{
    console.log(this);
}

func();

print empty object i.e. {} without adding "use strict" .


6) undefined variable

    "use strict";
    x= 10
    console.log(x);

    variable x is assigned value before declaration.
7) function param duplication
    "use strict";
    function MyFunc (i1,i2,i3,i1)
    {
       console.log(i1);
    }

    MyFunc(10,20,30,40);

       parameter i1 is put twice in function defination , value of i1 40 override its
       initial value 10

8) reserved keyword
     "use strict";
      var package = 1500;


      here "package" is reserved keyword in javascript.