-2

I'm trying to access one parameter from a function and use it in another function but I can't access the parameter outside of its original function. The other function is not able to see the parameter even when I return it.

function GiveBCount(a,b){
  a; //do something that has nothing to do with b. 
 //a is not a number
  var b = 0;
  b++;//increase b. 
      //b is a number.
  return b;
}

function TakeBCount(){
  if ( b > 0){
    //do something
  }
}

What is expected is that I want to be able to access the result of b that is in the GiveBCount() function inside of the TakeBCount() function

Joan
  • 413
  • 1
  • 5
  • 16

2 Answers2

0

you may try something like:

function GiveBCount(a){ // no need to take b here as you are declaring below
  a; //do something that has nothing to do with b. 
  var b = 0;
  b++;//increase b. 
      //b is a number.
  return b;
}

function TakeBCount(){
var b = GiveBCount(1);
  if ( b > 0){
    //do something
  }
}
Vishnu
  • 897
  • 6
  • 13
0

I have provided a way to achieve what you were trying to do with your code. I have added some comments below. Possibly take a quick read of the difference between local and global variables :)

function giveBCount(a,b){
    b++; // b now = 1
    return b;
}

function takeBCount(a,b){
    var giveBCountResult = giveBCount(a,b); // You now have access to the value.
    // e.g
    console.log(giveBCountResult);

    return giveBCount(a,b); // going to return the result from GiveBCount
}

var aCount = 1; // Global variable
var bCount = 0; // Global variable that will be changed from the functions

var result = takeBCount(aCount, bCount); // Call takeBCount function.

Good luck and enjoy learning JavaScript :)

Spangle
  • 762
  • 1
  • 5
  • 14