0

So I have a bunch of variables such as:

var HelloBob = '123';
var HelloSally = 'abc';
var HelloTim = 'pie';

I need to reference these variables by constructing their names and so having their names in another variable.

So in which this would output '123' instead of 'Hellobob'

var name = 'bob';
console.log('Hello'+bob)

I've done this previously using Window[] (I think), but I attempt using it and it doesn't work. Such as...

var HelloBob = '123';
var name = 'bob';
if(typeof window['Hello'+name] !== undefined){
   console.log('Variable Exists')
}

Which should only be true if a variable with the name 'Hellobob' exists, but it is always true when I run it.

I'll need to be able to reference the variables fully, so able to do .toLowerCase()

Vereonix
  • 1,341
  • 5
  • 27
  • 54
  • 2
    why not collect all values as properties of a custom object, this is easily accessable, without the need for beeing global. – Nina Scholz Dec 19 '18 at 18:07
  • `typeof something` returns a string, which is `!== undefined`, but is `== "undefined"` – Reinstate Monica Cellio Dec 19 '18 at 18:07
  • 2
    No, Hellobob does not exist. HelloBob does – Taplar Dec 19 '18 at 18:07
  • 3
    Code that is organized around variable names like this has a strong code smell. You should be using real data structures like objects for this. Everything will be easier to code, read, maintain and will be less fragile. – Mark Dec 19 '18 at 18:10

2 Answers2

4

There are a couple issues with your snippet:

  • typeof returns a string - you’re comparing the result to undefined (a property of the global scope) instead of 'undefined' (the type string)
  • You’re forming the variable name Hellobob which doesn’t exist. Setting name to Bob (instead of bob) should fix this.

var HelloBob = '123';
var name = 'Bob';

if (typeof window['Hello' + name] !== 'undefined') {
  console.log('Variable exists:', window['Hello' + name]);
}

However...

As mentioned in the comments, this is usually not a good pattern to follow. Instead, consider creating an object to contain these variables:

var hello = {
  Bob: '123',
  Sally: 'abc',
  Tim: 'pie',
};

var name = 'Bob';

if (hello.hasOwnProperty(name)) {
  console.log('Variable exists:', hello[name]);
}
MTCoster
  • 5,868
  • 3
  • 28
  • 49
  • uhh `undefined` is *not* an object, but you're right generally. The `null` constant is termed an "object" by `typeof`, but that's just a long-time weirdness. – Pointy Dec 19 '18 at 18:10
  • @Pointy Good point, is my update more accurate? – MTCoster Dec 19 '18 at 18:12
  • In reference to your first code, this never passes the if check for me, I've found the project where I previously use window[] and the code there doesn't work in my current project. I do "console.log(window['Hello' + name]);" with your corrected code and it out puts 'undefined' – Vereonix Dec 20 '18 at 09:12
  • @Vereonix Can you provide a reproducible example? The snippet in my answer appears to work fine – MTCoster Dec 20 '18 at 14:50
-3

The best way I know is to use eval:

var HelloBob = '123';
var HelloSally = 'abc';
var HelloTim = 'pie';

function getGreeting(name) {
    var greetingVar = 'Hello'+name;
    var greeting = null;
    try {
        greeting = eval(greetingVar);
    } catch (err) {
        console.error("Tried to get greeting for a person that doesn't exist.");
    }
    return greeting;
}

console.log(getGreeting('Bob'));
console.log(getGreeting('Scott'));

See also: Use dynamic variable names in JavaScript

Edit: I agree with other comments though, this seems like a terrible idea that is probably best implemented another way.

Scott E
  • 13
  • 1
  • 4
  • This could not be less relevant and could not be worse advice. The problem that the OP has is merely a couple of missing quotation marks. I don't know who upvoted this but they should really, **really** pay attention to what they're voting on. – Reinstate Monica Cellio Dec 19 '18 at 18:15
  • There's no reason to use eval here. – Taplar Dec 19 '18 at 18:17
  • Doesn't the window[] reference depend on the variables being globals run in a browser environment? Is that really a better solution than eval? – Scott E Dec 19 '18 at 18:18
  • Considering that `eval()` actually executes whatever you pass to it, yes, `window[varname]` definitely is better, even if it fails due to scope. – Reinstate Monica Cellio Dec 19 '18 at 18:19
  • Yes, that could certainly be a security concern in the real world. Fair point. – Scott E Dec 19 '18 at 18:25