- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Access variables from parent scope in anonymous PHP function
- How to preserve variables in a JavaScript closure function?
- How to access a local variable from a different function using C++ pointers?
- Function returning another function in JavaScript
- How to access a function property as a method in JavaScript?
- How to pass event objects from one function to another in JavaScript?
- How to define a JavaScript function using Function() Constructor?
- How to access variables from enclosing class using lambda in Java?
- Accessing variables in a constructor function using a prototype method with JavaScript?
- How to delay a JavaScript function call using JavaScript?
- PHP – How to subtract one arbitrary precision number from another using bcsub() function?
- How to call a parent window function from an iframe using JavaScript?
- How to copy the palette from one image to another using imagepalettecopy() function in PHP?
- How to call a JavaScript function from C++?
- How to create a function that invokes each provided function using JavaScript?

Advertisements