1

I am trying to update the contents of a variable in nodejs with the use of a string. In client side javascript this was done with the use of window[variable] however since there is no "window" in nodejs. I tried using "this" and "module", however all im getting is an empty object. need help thanks

Code Snippet:

var myVariable = 'Hello';
var exchangeVariable = 'myVariable';

this[exchangeVariable] = 'Hello World';

/*
    myVariable should equal to 'Hello World!'
*/

Thanks!

1
  • 1
    What's your purpose for accessing the variable in such a way? Commented Apr 30, 2012 at 1:29

2 Answers 2

13

Here's some background before I answer your question directly:

In JavaScript, objects can be either indexed by the dot notation (someObj.property) or by indexing them as you do in your example (someObj["property"])

In the browser, window is the global context that the browser evaluates your code within. Node uses a variable called global.

So, if you want to reference a variable you've defined globally:

> var someGlobalVar = "hi";
> var myLookupKey = "someGlobalVar";
> global[myLookupKey]
'hi'

However, this is generally considered very bad practice (in Node and the browser). There are a myriad of reasons for this, but I'm focusing on just one:

In Node, modules (each required file) should be treated as if they do not share global state (and in some cases, they cannot share state). I encourage you to read through the modules section of the node documentation if you are trying to share state across files.

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

2 Comments

Strange that this answer is voted down... It LGTM, at least to stay at 0. I'd vote it up just for the "Day of The tentacle" avatar ;)
It always makes me smile when someone recognizes it :)
0

You could create your own variables hash or array and assign the variable yourself.

var myVariable = "Hello";
var varArray = new Array()
    varArray["exchangeVariable"] = myVariable;

2 Comments

Why an Array? A blank object would be a lot more applicable to this use. You're not taking advantage of any of Array's behavior here
I said hash or array, I don't know of his use case. I just chose to write an array as an example.

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.