MaiaVictor
MaiaVictor

Reputation: 52987

How to set a variable on node.js if it's name is in other variable?

On the browser I can use the window object. How to do this on node.js?

var name="test"; 
var <name> = 3; 
print(test); 
//output: 3

Upvotes: 0

Views: 169

Answers (1)

Anatoliy
Anatoliy

Reputation: 30073

I can't do this in node in any local scope, but you can do this in global scope (like in browser window object):

var name = 'test';
global[name] = 3;
console.log(test); // 3
console.log(global['test']); // 3;

So, global object exactly the same as browser window object.

Difference is: in browser when you declaring var test = 2 in top-level scope you actually creating window['test'], but in node you don't, because every module scoped with function call by default.

Upvotes: 1

Related Questions