Neha
Neha

Reputation: 93

Passing values among functions

I have written a some code in javascript, however I do not understand how values are passed between functions. Sorry about the query, but I tried searching, and did not quite understand what was happening.

Here is something like what i want to do :

function check() {
    var x = "one";
    if (condition) 
    x = "two";
    //return x;
}

function compute() {
    maximum = 100;  //global
    var current = document.getElementById('test').value;
        var output = maximum/current;
        if(x == "one") Foo1();
        else Foo2();
}

function Foo1() {
    //code using value of ouput
}

var i=0;

function Foo2() {
    setTimeout(function () {
        //code
        i++;
        if (i < output) Foo2();
    }, 1000)
}

I want the value of x to go to compute() and accordingly when condition is checked, go to either Foo1 or Foo2, and the value of output to go to these functions(Foo1 or Foo2).

Upvotes: 1

Views: 75

Answers (1)

jfriend00
jfriend00

Reputation: 707356

It sounds like you need some real basics in javascript functions and parameters.

Here's a simple example:

function step1() {
    var x = 3;   // This is a local variable.  It is not accessible anywhere outside
                 // this function unless it is passed as a parameter to a function call

    step2(x);    // Call step2, passing it a parameter
}

function step2(p) {
    // When this function starts, the parameter p will have whatever value
    // was passed in the function call.
    // In this particular example, it will initially have the value of 3.

    console.log(p);    // outputs 3

    p = p + 3;    // add three to the current value
    step3(p);     // call step3, passing it a parameter
}

function step3(r) {
    console.log(r);    // outputs 6
}

step1();    // call the first function

Upvotes: 2

Related Questions