Is there any purpose to redeclaring JavaScript variables?

前端 未结 9 1768
傲寒
傲寒 2020-12-11 18:38

I am new to JavaScript.





        
相关标签:
9条回答
  • 2020-12-11 18:54

    As far as my understanding of javascript goes, the use of the var keyword is completely optional in the global scope. It's a different story for functions.

    When inside a function, use the var keyword to indicate that the variable is local to the function (as opposed to being global by default).

    I personally use var in the global scope to show that a variable is being declared and/or utilized for the first time.

    You can reference http://www.w3schools.com/js/js_variables.asp for more info.

    0 讨论(0)
  • 2020-12-11 19:02

    That second var x is totally superfluous.

    0 讨论(0)
  • 2020-12-11 19:02

    Also, a programmer might want to use var to localize a variable:

    <script>
    var x= 'this is global x';
    function my_x() {
     var x= 'localized x';
     alert(x);
    }
    my_x();
    alert(x);
    </script>
    
    0 讨论(0)
  • 2020-12-11 19:04

    You should never redeclare a variable within the same scope, if you really want to change this then assign to it. Redeclaration is not required to create a different object in this dynamic language, if you want x to be a string just assign:

    x = "hello";
    

    It is not required that you set it back to undefined or redeclare first.

    Please note that changing the variable type is not very good practice in most situations, simply stating that it is a possibility if that's what you require.

    0 讨论(0)
  • 2020-12-11 19:09

    You aren't really re-declaring the variable.

    The variable statement in JavaScript, is subject to hoisting, that means that they are evaluated at parse-time and later in runtime the assignments are made.

    Your code at the end of the parse phase, before the execution looks something like this:

    var x;
    x = 5;
    
    document.write(x);
    document.write("<br />");
    document.write(x);
    
    0 讨论(0)
  • 2020-12-11 19:11

    Within the same scope, it is totally unnecessary to "redeclare" a variable.

    0 讨论(0)
提交回复
热议问题