0

I have an idea, but need some instruction to do it.

I want to use in variable in function then use it in another function. Let me explain:

myfunction() {

....

var explain = "yes";

}


myfunction2() {

if ( explain == "yes") {

...
}
}
2
  • Either broaden its scope or pass it in. Commented Aug 10, 2020 at 22:54
  • why not pass explain as one parameter of myfunction2? Commented Aug 10, 2020 at 22:55

4 Answers 4

1

define explain outside of myFunction(), here's an example:

var explain = "yes";

myfunction() {

....

}

myfunction2() {

if ( explain == "yes") {

... } }
Sign up to request clarification or add additional context in comments.

Comments

1

You have two choices: either make the variable global (or move it up to the lowest scope accessible by both functions) or pass it as an argument to the second function.

Option 1:

var explain;
function myfunction() {
    explain = "yes";
}
function myfunction2() {
    if ( explain == "yes") {
       //...
    }
}
myfunction();
myfunction2();

Option 2:

function myfunction() {
    var explain = "yes";
    myfunction2(explain);
}
function myfunction2(explain) {
    if ( explain == "yes") {
       //...
    }
}
myfunction();

Comments

1

You can simply make the variable in one function and call it in other function like the following:

function myfunction() {
  window.value = 'yes'; //declaring global variable by window object
}

function myfunction2() {
  console.log(window.value); //accessing global variable from other function  
  if (window.value == 'yes') {
    console.log('Run')
  }
}
myfunction();
myfunction2();

Comments

1

There are 2 possibilities:

1. Declare it as global.

var explain;

function myfunction() {
    explain = "yes";
}

function myfunction2() {
    if ( explain == "yes") {
         console.log('yes');
    }
}

myfunction();
myfunction2();

2. Use the variable as return and function-parameter.

function myfunction3() {
    let explain2 = "yes";
     return explain2;
}

function myfunction4(explain2) {
    if ( explain2 == "yes") {
         console.log('yes');
    }
}

let explain2 = myfunction3();
myfunction4(explain2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.