skip to Main Content

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


  1. 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 in myFunction. 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.

    Login or Signup to reply.
  2. One solution is simply store your variables in key/value pairs and then you can access them in loops or directly.

    var labor_rate = 25;
    var k1 = labor_rate
    
    function myFunction() {
        let vars = {
            labor_rate2 : 25,
            k12 : 25
        }
        console.log(vars)
    }
    
    
    myFunction()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search