How to list variables defined within a Javascript scope?

Asked

Viewed 954 times

8

How do I know/list which variables have already been defined within a scope, whether global or local?

For example if I set var x, y, z = 10, the result of a possible command to list the variables already defined should be something like a array with their names: ["x", "y", "z"].

It is possible to do this in Javascript?

In R, for example, this command would be ls() and return a vector of strings with the names of the variables.

3 answers

7

As @bfavareto also mentioned this is not possible in Javascript. However, if you plan your code well using a placeholder you can do this check. However, variables within functions are not accessible to outside scopes.

var namespace = {
    minhafuncao1: function () {

    },
    minhavariavel1: 100
}

for (variable in namespace) {
    console.log(variable);
}

Gives:

minhafuncao1 
minhavariavel1 
  • This could be really interesting.

6


This is not possible in Javascript, because the objects where the variables are stored (Environment Records) are not available to the language user except in the case of the global object. But even in this case, listing the properties of the global object will include all global variables, not just the ones you created. For example:

var a = 10;
for(i in window) {
    if(window.hasOwnProperty(i)) console.log(i)
}

Output will include your variable a, but also includes document, localStorage, name, etc..


You can partially circumvent this problem by passing on the object arguments from one function to the other. For example:

function soma(a, b) {
    return a + b;
}

function subtrai(a, b) {
    return a - b;
}

function somaOuSubtrai(a, b) {
    // Transforma os argumentos de objeto para array, esperada pelo apply.
    // Não é 100% necessário, mas garante compatibilidade com implementações antigas
    var args = Array.prototype.slice.call(arguments);

    if(a >= b) {
        return subtrai.apply(null, args);
    } else {
        return soma.apply(null, args);
    }
}

somaOuSubtrai(1,3); // 4
somaOuSubtrai(3,1); // 2

Another alternative is to package your variables as properties of an object (a namespace), as suggested by @Sergio. In the end you may end up using a combination of these strategies.

  • Strange this. How, for example, to apply a function in a set of several variables? You will have to write all manually in the script?

  • Yes, you have to list them one by one when applying the function. An exception is if you want to pass on the arguments received by a function, in this case it is possible to apply another function directly to the object arguments of the first.

  • @Carloscinelli I added an example of what is possible to do with the arguments, maybe it is close to what you are needing.

  • @bfavarreto, thanks a lot!

3

Yes and nay. Not in almost all situations. Yes, but only to a limited extent if you want to check the overall range. See the following example:

var a = 1, b = 2, c = 3;

for ( var i in window ) 
{
    console.log(i, typeof window[i], window[i]);
}

Which generates, between 150+ other things, the following:

getInterface function getInterface()
i string i // <- Veja aqui!
c number 3
b number 2
a number 1 // <- Outro...
_firebug object Object firebug=1.4.5 element=div#_firebugConsole
"Firebug command line does not support '$0'"
"Firebug command line does not support '$1'"
_FirebugCommandLine object Object
hasDuplicate boolean false

That’s why, it is possible to list some variables in the current scope, but it is not reliable, efficient, or easily accessible.

The best question is why you want to know what variables are in the scope?

Original response in English

Browser other questions tagged

You are not signed in. Login or sign up in order to post.