-1

I realize there is no way to get a dictionary of local variables in a javascript function, and no equivalent of python's locals(). However, is there a way to write a function that would assist in this. For example, something like:

var a = 1;
var b = 2;

var output = locals(a, b);
console.log(output);

And output would be a dictionary with all the variables:

{
    "a": 1,
    "b": 2
}

Or, any other way apart from me manually creating a map, and inserting each field.

6
  • Can you use array for this? Commented Nov 25, 2019 at 18:32
  • stackoverflow.com/questions/17276206/… Commented Nov 25, 2019 at 18:33
  • As the questions you link to say: No. JS provides no mechanisms for inspecting what variables exist (other than globals when they are added to the default object as a side-effect) Commented Nov 25, 2019 at 18:35
  • 1
    If you are going to make a static function call, referencing the variables, you can use the short property syntax of the object literal: const output = { a, b } Commented Nov 25, 2019 at 18:36
  • @Quentin, I am not asking to inspect the variables in scope. I understand that is not possible. I am asking if there is a way to create a helper method to assist with creating a dictionary of specified local variables. The method will be passed all the variables of interest. So, this question is not really a duplicate. Commented Nov 25, 2019 at 18:39

1 Answer 1

4

No.

Since you can't pass variables (only values) the data passed to such a function would be 1 and 2 with no association with the variable name.

You can, however, use the shorthand object syntax:

const output = { a, b };

… where an identifier without a value will take its value from the variable of the same name.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.