0

I was testing a script and had a problem with a specific part. I isolated the part that was giving me problems.

var target_army = "0";

function test(){
    if (target_army == "0") {
        var target_army = "1";
        alert (target_army);
    } else {
        alert ("nope");
    }
}

The function runs the alert "nope nope" while target_army should be 0. The part

var target_army = "1";
alert (target_army);

runs fine but with the addition of the if statement it goes wrong. Does anyone have an idea where I dun-goofed?

Ivaldir
  • 185
  • 12
  • This code doesn't make sense to me. Where are you even calling this function? Why are you creating a local variable with the same name as a global variable? (That seems like it's just asking for bugs.) What does "it goes wrong" mean? You need to describe the problem. – David Feb 17 '16 at 20:05
  • in javascript, don't rely on `==`. If you know the types, and you should, use `===` instead. The first tests whether JS can convert one into the other, using whatever conversions it is allowed to do, so "" == 0 because both of those can be transformed into `false`, which is almost never what you want. – Mike 'Pomax' Kamermans Feb 17 '16 at 20:05
  • @David he's not calling the function, the function is calling him. that's why it looks confusing – Abdul Ahmad Feb 17 '16 at 20:07

1 Answers1

1

Your function test is actually interpreted like this:

function test(){
    var target_army;  // local variable declaration - hoisting! [1]
    if (target_army == "0") {  // the local variable target_army doesn't equal 0
        target_army = "1";
        alert (target_army);
    } else { // so it's a nope
        alert ("nope");
    }
}

[1] https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

your mistake is using var inside the function instead of modifying the global variable like this:

var target_army = "0";

function test(){
    if (target_army == "0") { // now the global target_army is copared
        target_army = "1";  // and modified
        alert (target_army);
    } else {
        alert ("nope");
    }
}
pawel
  • 35,827
  • 7
  • 56
  • 53