I’m attempting to output all of the variables in my script along with their values.
The for statement below works for the variables that are not in the function. How do I get the values of the variables inside the function? Specifically k12, which I would expect to output: var k12 = 25
var labor_rate = 25;
var k1 = labor_rate
function myFunction() {
var labor_rate2 = 25;
var k12 = labor_rate2
}
// output all variables
var variables = {};
for(var b in window) {
if(window.hasOwnProperty(b)) {
console.log(b+" = "+window[b]);
variables[b] = window[b];
}
}
2
Answers
You can’t, and it doesn’t make sense to want to.
The variables in
myFunction
don’t exist, unless the thread of execution is inmyFunction
. When the thread of execution leaves the function, those variables cease to exist.At the point in time where you’re printing variables, the variables you’re looking for don’t exist and don’t have a value for you to print, even if you’re previously invoked the function.
One solution is simply store your variables in key/value pairs and then you can access them in loops or directly.