Thursday 15 April 2010

Are there downsides to using var more than once on the same variable in JavaScript -


Before asking my questions, I want to make a disclaimer I know what var does , I know about block scope, and I know about moving the variable I am not looking for answers to those topics

I'm just thinking that more than one variable within the function But using a variable declaration is a functional, memory or performance cost.

Here's an example:

  function foo () {var i = 0; Whereas (i ++ & lt; 10) {var j = i * i; }}   

The last code can be easily written j variabled has been declared at the top:

  function Foo () {Var i = 0, j; While (i ++ & lt; 10) {j = i * i; }}   

I am thinking that there is no real difference between these two methods. In other words, does var do anything other than the scope of the keyword?

For this reason I have heard the second method to like:

  1. The first method gives the scope of the block when it actually works scoped.
  2. Variable dispersion is hoisted at the top of the scope, so it should be defined where.

    I consider these reasons as good, but are primarily stylish other reasons which work more with functionality, memory allocation, performance etc.?

    There will be no difference during the execution time . Interpreting / compiling time can be a susceptible small difference, but surely implementation will depend. Some bytes in the file size can also be different, which can affect download time. I do not think there is any concern about any of these.

    As you already know, any variable declaration will be hoisted at the top of the function. The important thing to note is that is done during the interpretation / compilation process, not during execution. Before the

    function is executed, the function should be parsed after every function is parsed, all the variables will take declaration declarations to the top of which It means that they will be identical and there will be no execution time cost.

    For this reason, there will be no memory cost differences after parsing, no difference will be.


    Since you are not asking about style, I am not telling you what I think is better. But I would say that the only reason you should prefer more than one is style.

No comments:

Post a Comment