-1

How can I use the local variable randomNum declared in the first function in second function?

btn.click(function() {
  var randomNum = Math.floor(Math.random() * (3-0)) + 0;
})

rock.click(function() {
  // i want to use `randomNum` variable from the above function
});
j3ff
  • 5,719
  • 8
  • 38
  • 51
Satyam Saurabh
  • 488
  • 4
  • 16
  • https://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-should-i-use-it-or-omit-it – Quentin Apr 11 '20 at 20:21

2 Answers2

1

The easiest way would be to declare the variable outside of the function, so it will be in scope of both functions

Though remember, randomNum would equal undefined until btn.click() is fired.

See this JSFiddle for an example: https://jsfiddle.net/Lo8c2mrq/

var randomNum

btn.click(function(){
  randomNum = Math.floor(Math.random() * (3-0)) + 0;
})

rock.click(function(){
  console.log(randomNum) // undefined, or the number that was assigned from btn click
});
Oli
  • 852
  • 6
  • 12
  • i actually want to use the random number generated by the first function when the btn.click() is fired in second function. Can you tell me how ? – Satyam Saurabh Apr 12 '20 at 09:30
  • This answer shows you how. I updated the answer with a JSFiddle, so you can see the second function is using the value set by the first function: https://jsfiddle.net/Lo8c2mrq/ – Oli Apr 12 '20 at 11:28
0

You could create a separate function getRandomNum(), so you would be more flexible in case you want to change the value of randomNum in future. Global variable are bad in most cases, as it will be hard to track which function or part of code actually changes it.

var getRandomNum = function () {
  // set randomNum once
  if (typeof this.randomNum === 'undefined') {
    this.randomNum = Math.floor(Math.random() * (3 - 0)) + 0;
  }
  return this.randomNum;
};

btn.click(function () {
  var randomNum = getRandomNum();
})

rock.click(function () {
  console.log(getRandomNum());
});
Felix Hagspiel
  • 2,634
  • 2
  • 30
  • 43