Javascript: server-side dynamic variable names

How do I create dynamic variable names in NodeJS? Some examples say storing in a window variable, but I assumed it was client-side Javascript. Correct me if I am wrong.

+6
source share
2 answers

Usually you do something like:

 var myVariables = {}; var variableName = 'foo'; myVariables[variableName] = 42; myVariables.foo // = 42 
+14
source

In node.js, there is a global context, which is the equivalent of the window context in js on the client side. Declaring a variable outside of any closing module / function /, as in normal Javascript, will contain it in a global context, that is, as a global property.

I understand from your question that you want something similar to the following:

 var something = 42; var varname = "something"; console.log(window[varname]); 

This in node.js will become:

 var something = 42; var varname = "something"; console.log(global[varname]); 
+4
source

Source: https://habr.com/ru/post/926261/


All Articles