Declare var before assigning multiple values in Javascript?
javascript
Solution
javascript does not have block scope, so declaring variables in a switch block does not work like you would expect.
furthermore, due to variable hoisting, all variable declarations in a function block are hoisted to the top by the interpreter and your code would look like this:
function test1() {
var test;
var test;
switch(type) {
case 1:
test = "Hello One"
break;
case 2:
test = "Hello Two"
break;
}
}
After performing the hoist, it is easy to see why the first block is incorrect.
Problem
In Javascript, which format of `var` declarations 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; } } ``` In test2(), there is 1 extra line of code to declare `test` as a `var` before assigning a value, but this saves having to declare `var test` twice. Is either way better than the other?