How to access variables declared in a function, from another function using JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We have to write a function, that does some simple task, say adding two numbers or something like that. We are required to demonstrate the way we can access the variables declared inside that function in some other function or globally.

Example

Following is the code −

const num = 5;
const addRandomToNumber = function(num){
   // a random number between [0, 10)
   const random = Math.floor(Math.random() * 10);
   // assigning the random to this object of function
   // so that we can access it outside
   this.random = random;
   this.res = num + random;
};
const addRandomInstance = new addRandomToNumber(num);
const scopedRandom = addRandomInstance.random;
const result = addRandomInstance.res;
// must be equal to the original value of num i.e., 5
console.log(result - scopedRandom);

Output

Following is the output in the console −

5
raja
Published on 18-Sep-2020 09:44:57
Advertisements