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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With