0

I'm trying to get variable d value from function b in function e, but the result not value from function b. The result just from variable outside the function b.

var d = "maybe";
var a = 1;

function b() {
    if (a == 1) {
        var d = "yes";
    } else {
        var d = "no";
    }
}
b();

function e() {
console.log(d); //output maybe
}
e();

How do I get the result to be the value from function b, or equal to "yes"?

Vickel
  • 7,879
  • 6
  • 35
  • 56
Ras
  • 991
  • 3
  • 13
  • 24

1 Answers1

0

You only have to use the var keyword when you define the variable. If you want to change the variable afterwords, don't use var. If you do you'll actually be making a new variable inside the function. So the code you want is:

var d = "maybe";
var a = 1;

function b() {
    if (a == 1) {
        d = "yes";
    } else {
        d = "no";
    }
}
b();

function e() {
    console.log(d); // now it outputs yes
}
e();
Anonymous
  • 491
  • 2
  • 12