Anders Kitson
Anders Kitson

Reputation: 1545

Trying to return a variable outside of a function

I am pretty sure I am doing this wrong but what I want to happen is onload i want function test to run then function one then function two, and then I want function two to return var abc from function one.

window.onload=function(){
  test();
};

function test(){
    var abc;
  function one(){
    abc = 1;
    two();
  }
  function two(){
    console.log(abc);
  }

}

Upvotes: 0

Views: 37

Answers (2)

Bergi
Bergi

Reputation: 664297

i want function test to run then function one

That's the step you were missing. Your test function currently only declares function one, but never calls it.

function test() {
    var abc;
    function one() {
        abc = 1;
        two();
    }
    function two() {
        console.log(abc);
    }
    one(); // call it!
}
test(); // logs 1

There might be better ways to share values between functions than closure (depending on the use case), but this does what you want.

Upvotes: 1

ShaneQful
ShaneQful

Reputation: 2236

You have only declared function one you need to executed it. At the end of the test function add one(); see below:

window.onload=function(){
    test();
};

function test(){
    var abc;
    function one(){
        abc = 1;
        two();
    }
    function two(){
        console.log(abc);
    }
    one();//execute function 1
}

Upvotes: 1

Related Questions