Consider the following code:
var factory = function(someCondition) {
var para1 = 'some value';
if(someCondition)
var para2 = 'some other value';
return new MyClass(para1, para2);
}
I know that this code is perfectly legal, even though para2
is declared inside the if
but used outside.
My question is: Is this - although legal - considered bad style by major Javascript style guides? If so, by which and what are the proposed alternatives?
Just to be clear: I know about hoisting and the fact that variables are not block scoped but function scoped.
Technically the variable is "hoisted", the code will execute like this:
var para1 = 'some value';
var para2;
if(someCondition)
para2 = 'some other value';
All var
declarations inside a scope declare variables in this scope before code is executed. As such, it doesn't make much of a difference in practice. However, I'd consider it good style to write the code explicitly as above to make it obvious what variables exist in the scope. "Hiding" variable declarations inside conditions can lead to confusion.
That should not be a bad style, this could be a bit confusing.
Any way javascript will do it like bellow because of hoisting, So better write also like bellow.
var factory = function(someCondition) {
var para1 = 'some value';
var para2; //declare it here
if(someCondition)
para2 = 'some other value'; //assign the value here
return new MyClass(para1, para2);
}
The ES6 version introducing a new keyword let which gives variables block scoping.
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