Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable in if and use outside

Tags:

javascript

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.

like image 995
Daniel Hilgarth Avatar asked Dec 20 '22 11:12

Daniel Hilgarth


2 Answers

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.

like image 157
deceze Avatar answered Jan 05 '23 08:01

deceze


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.

like image 39
Mritunjay Avatar answered Jan 05 '23 10:01

Mritunjay