- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to access variables declared in a function, from another function using JavaScript?
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
Advertisements