Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to access variables declared in a function, from another function using JavaScript?
In JavaScript, variables declared inside a function are scoped to that function and cannot be directly accessed from outside. However, there are several ways to make these variables available to other functions or globally.
Problem with Function Scope
Variables declared inside a function are private to that function:
function myFunction() {
let localVar = "I'm inside the function";
}
myFunction();
// console.log(localVar); // This would cause an error
Using Constructor Functions with 'this'
You can use constructor functions to expose internal variables as properties:
const num = 5;
const addRandomToNumber = function(num) {
// a random number between [0, 10)
const random = Math.floor(Math.random() * 10);
// assigning values to this object so we can access them outside
this.random = random;
this.res = num + random;
};
const addRandomInstance = new addRandomToNumber(num);
const scopedRandom = addRandomInstance.random;
const result = addRandomInstance.res;
console.log("Random:", scopedRandom);
console.log("Result:", result);
console.log("Original num:", result - scopedRandom);
Random: 7 Result: 12 Original num: 5
Using Return Values
Return an object containing the variables you want to access:
function addRandomToNumber(num) {
const random = Math.floor(Math.random() * 10);
const result = num + random;
// Return an object with the values
return {
random: random,
result: result
};
}
const data = addRandomToNumber(5);
console.log("Random:", data.random);
console.log("Result:", data.result);
console.log("Original num:", data.result - data.random);
Random: 3 Result: 8 Original num: 5
Using Closures
Closures allow inner functions to access variables from their outer scope:
function createCounter() {
let count = 0;
return {
increment: function() {
count++;
return count;
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2
1 2 2
Comparison of Methods
| Method | Use Case | Advantages |
|---|---|---|
| Constructor Function | Creating multiple instances | Clear object-oriented approach |
| Return Object | One-time data access | Simple and direct |
| Closures | Maintaining private state | Data encapsulation |
Conclusion
Use constructor functions with this for object instances, return objects for simple data sharing, and closures for maintaining private state. Choose the method that best fits your specific use case.
