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

前端 未结 28 3178
半阙折子戏
半阙折子戏 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:45

    The main reasons why developers should use "use strict" are:

    1. Prevents accidental declaration of global variables.Using "use strict()" will make sure that variables are declared with var before use. Eg:

      function useStrictDemo(){
       'use strict';
       //works fine
       var a = 'No Problem';
      
       //does not work fine and throws error
       k = "problem"
      
       //even this will throw error
       someObject = {'problem': 'lot of problem'};
      }
      
    2. N.B: The "use strict" directive is only recognized at the beginning of a script or a function.
    3. The string "arguments" cannot be used as a variable:

      "use strict";
      var arguments = 3.14;    // This will cause an error
      
    4. Will restrict uses of keywords as variables. Trying to use them will throw errors.

    In short will make your code less error prone and in turn will make you write good code.

    To read more about it you can refer here.

提交回复
热议问题