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

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

    Strict mode can prevent memory leaks.

    Please check the function below written in non-strict mode:

    function getname(){
        name = "Stack Overflow"; // Not using var keyword
        return name;
    }
    getname();
    console.log(name); // Stack Overflow
    

    In this function, we are using a variable called name inside the function. Internally, the compiler will first check if there is any variable declared with that particular name in that particular function scope. Since the compiler understood that there is no such variable, it will check in the outer scope. In our case, it is the global scope. Again, the compiler understood that there is also no variable declared in the global space with that name, so it creates such a variable for us in the global space. Conceptually, this variable will be created in the global scope and will be available in the entire application.

    Another scenario is that, say, the variable is declared in a child function. In that case, the compiler checks the validity of that variable in the outer scope, i.e., the parent function. Only then it will check in the global space and create a variable for us there. That means additional checks need to be done. This will affect the performance of the application.


    Now let's write the same function in strict mode.

    "use strict"
    function getname(){
        name = "Stack Overflow"; // Not using var keyword
        return name;
    }
    getname();
    console.log(name); 
    

    We will get the following error.

    Uncaught ReferenceError: name is not defined
    at getname (:3:15)
    at :6:5
    

    Here, the compiler throws the reference error. In strict mode, the compiler does not allow us to use the variable without declaring it. So memory leaks can be prevented. In addition, we can write more optimized code.

提交回复
热议问题