Javascript: dynamically named global variable

dynamic-data, global-variables, javascript

Solution

window['socket_'+userId] = "whatever";

That should work just fine. Do NOT use `eval` for something as trivial as this.

Although, even better would be an array:

socket[userId] = "whatever";

Problem

I have a global variable which looks like this: ``` var socket_x = 'whatever'; ``` The thing is that "x" would depend on the user session. Let's say the user id is 123, i want the global variable to be: ``` var socket_123 = 'whatever'; ``` This way, each user browsing will have his own socket set as global variable. I just don't know how to do this. I know I can use: ``` eval('socket_' + userId) = 'whatever'; //not recommended window['socket_' + userId] = 'whatever'; //best ``` but if I want to declare the global variable like this, it won't work: ``` var eval('socket_' + userId) = 'whatever'; ``` Can someone help me on this one? Thank you. PS: I know "eval" should not be used for this but it's just for the illustration sake. EDIT: Thank you for your answer, all of you, but it just doesn't work. This is what I have so far for my global variable (it works as it is but I don't want to mix php with javascript): ``` var socket_<?php echo $_SESSION['user_id'];?> = io.connect( 'http://pubsub.pubnub.com', pubnub_setup_private ); ``` if I do this instead, like you suggest: ``` window['socket_'+actual_user_id]= io.connect( 'http://pubsub.pubnub.com', pubnub_setup_private ); ``` it just won't work. if I do this as a local variable, it works: ``` eval('socket_'+actual_user_id).emit( 'all', msg_all ); ``` But if I do that, it doesn't: ``` window['socket_'+actual_user_id].emit( 'all', msg_all ); ``` So I got 2 problems here: - window never works for me, eval does. - eval works as a local variable but not as a global one. It seems that "var" is needed but using "var" just before eval is not accepted. I'm ok with avoiding eval but I just don't know how. PS: I'm on a global context here.

Original source