Declare a variable in if and use outside

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 completely legal , although para2declared internally if, but used externally.

My question is: Is this - although legal - considered a bad style in the basic Javascript style guides? If so, what and what are the proposed alternatives?

Just to be clear: I know about the rise and that variables are not a scope, but a scope of functions.

+4
source share
5 answers

Technically, the variable is "raised", the code will be executed as follows:

var para1 = 'some value';
var para2;
if(someCondition)
    para2 = 'some other value';

var . , . , , , , . "" .

+5

, .

javascript , , - , , .

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);
}

ES6, let, .

+3

JavaScript 'hoisting':

var para2 = "my value";

var factory = function(someCondition) {
    var para1 = 'some value';
    console.log(para2);
    if(someCondition)
        var para2 = 'some other value';

    return new MyClass(para1, para2);
}

factory(true); // undefined

log 'undefined'.

+2

JavaScript , :

var factory = function(someCondition) {
    var para1 = 'some value';
    var para2 = 'some other value';
    if(someCondition)
    {
        // some code..
    }

    return new MyClass(para1, para2);
}
+1

, .

 var factory = function(someCondition) {
    var para1 = 'some value';
    if(someCondition){
       var para2 = 'some other value';
       alert(para2);
    }

    alert(para2);
    return new MyClass(para1, para2);
 }

, . . if para2. , " "!. . , , , if, " "!.

This is what happens. Your variable para2 is declared internally if it is known as a block. A block is all that appears in open and closed brackets - {and}. In many programming languages, variables declared inside a block are part of its own area of ​​the block. This means that these variables are local and cannot be accessed outside the block.

JavaScript is not like many other programming languages. JavaScript does not support scope browsing.

More here

0
source

All Articles