0

Because of javascript variable hoisting, jshint complains about :

function test() {
    ...
    if( cond1 ) {
        var a = ...
        //do something with a
    }
    ...
    if( cond2 ) {
        var a = ...
        //do something with a
    }
    ...
}

because it's equivalent to :

function test() {
    var a;
    var a;
    ...
    if( cond1 ) {
        a = ...
        //do something with a
    }
    ...
    if( cond2 ) {
        a = ...
        //do something with a
    }
    ...
}

Does the first approach can lead to bugs in some code ?

Tom
  • 4,666
  • 2
  • 29
  • 48
  • 1
    I think this question http://stackoverflow.com/questions/1162561/whats-wrong-with-defining-javascript-variables-within-if-blocks/1162756 is exactly the same to your, so I'd recommend you read it. – Alex Todef Feb 26 '16 at 15:18
  • Yes an no, it may depends but i definitely wont recommend this. Javascript is permissive, so it'll accept you having 2 vars with the same name in the same scope, therefore whenever you'll try to do something with thoses vars, JS might not use the correct var. – Jorel Amthor Feb 26 '16 at 15:19
  • large enough chunks of code, if you think some variable is scoped to a particular block, but it isn't, you could get some bugs. – Jaromanda X Feb 26 '16 at 15:21
  • Everything that can be somehow unexpected to someone can lead to bugs. Reusing variables of the same name for different purposes can be error-prone as well when you forget the second initialisation. – Bergi Feb 26 '16 at 15:21
  • 1
    `JS might not use the correct var` - there will only ever be one – Jaromanda X Feb 26 '16 at 15:21
  • @AlexTodef Thank you, I do have read it, but it doesn't answer the question : can it lead to bug ? – Tom Feb 26 '16 at 15:21
  • @JaromandaX have an example in mind ? Because I don't find one, so I can't convince myself. – Tom Feb 26 '16 at 15:22
  • 1
    not really, I think as @Bergi said, it's more likely to be an issue if the second one is uninitialised - that is easy to show – Jaromanda X Feb 26 '16 at 15:25

0 Answers0