Declare var before assigning multiple values ​​in Javascript?

In Javascript, which var declaration format is better:

 function test1() { switch(type) { case 1: var test = "Hello One" break; case 2: var test = "Hello Two" break; } } 

Or:

 function test2() { var test; switch(type) { case 1: test = "Hello One" break; case 2: test = "Hello Two" break; } } 

There is another line of code in test2 () to declare test as var before assigning a value, but this saves the need to declare var test twice. Is the method better than the other?

+4
source share
3 answers

javascript does not have a block scope, so declaring variables in a switch block does not work as you expected.

In addition, due to the hoisting variable , all variable declarations in the function block are raised to the top by the interpreter, and your code will look like this:

 function test1() { var test; var test; switch(type) { case 1: test = "Hello One" break; case 2: test = "Hello Two" break; } } 

After the lift is completed, it is easy to see why the first block is incorrect.

+7
source

IMO the second is preferable.

This is more communicative and closer to what is actually happening (for example, a permutation of variables ).

I'm also not a fan of hiding variable declarations inside what looks like areas, but not.

+4
source

Your first code is incorrect; You specified the same variable several times.

JSHint will complain about it.

+2
source

Source: https://habr.com/ru/post/1495365/


All Articles