What does “use strict” do in JavaScript, and what is the reasoning behind it?

前端 未结 28 3087
半阙折子戏
半阙折子戏 2020-11-21 06:05

Recently, I ran some of my JavaScript code through Crockford\'s JSLint, and it gave the following error:

Problem at line 1 character 1: Missing \"use

28条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 06:32

    My two cents:

    One of the goals of strict mode is to allow for faster debugging of issues. It helps the developers by throwing exception when certain wrong things occur that can cause silent & strange behaviour of your webpage. The moment we use use strict, the code will throw out errors which helps developer to fix it in advance.

    Few important things which I have learned after using use strict :

    Prevents Global Variable Declaration:

    var tree1Data = { name: 'Banana Tree',age: 100,leafCount: 100000};
    
    function Tree(typeOfTree) {
        var age;
        var leafCount;
    
        age = typeOfTree.age;
        leafCount = typeOfTree.leafCount;
        nameoftree = typeOfTree.name;
    };
    
    var tree1 = new Tree(tree1Data);
    console.log(window);
    

    Now,this code creates nameoftree in global scope which could be accessed using window.nameoftree. When we implement use strict the code would throw error.

    Uncaught ReferenceError: nameoftree is not defined

    Sample

    Eliminates with statement :

    with statements can't be minified using tools like uglify-js. They're also deprecated and removed from future JavaScript versions.

    Sample

    Prevents Duplicates :

    When we have duplicate property, it throws an exception

    Uncaught SyntaxError: Duplicate data property in object literal not allowed in strict mode

    "use strict";
    var tree1Data = {
        name: 'Banana Tree',
        age: 100,
        leafCount: 100000,
        name:'Banana Tree'
    };
    

    There are few more but I need to gain more knowledge on that.

提交回复
热议问题