-1

I know how to check whether a variable in Javascript exists or not. I can simply use

if (variable == null) { // do something }

to check that it does not exist. Or similarly

if (typeof variable == 'undefined') { // do something }

But I'm in a slightly different situation: I have a variable named 'myVariable' which takes a string as value.

Question: How can I check whether a variable exists with a name equal to the value of myVariable?

Example: If we have

var myVariable = 'car';

how can I check whether a variable exists / is defined with the name 'car'? (Of course in practice we don't know the value of myVariable). I need something like

if (typeof value of myVariable == 'undefined') { // do something}

Thank you very much in advance for any help!

Joshua
  • 40,822
  • 8
  • 72
  • 132
Tall83
  • 343
  • 1
  • 4
  • 8
  • 1
    Why do you think you need to do this? It’s hardly ever a good idea. – Ry- Apr 01 '17 at 02:55
  • Possible duplicate of ["Variable" variables in Javascript?](http://stackoverflow.com/questions/5187530/variable-variables-in-javascript) – domsson Apr 01 '17 at 03:11
  • I really need it but it's difficult to explain. It's because I'm working on a project which involves different names for one object (depending where this object appears). However, I have to be able to handle all these object with one code (which fits for all the names). The details are difficult, but I can manage everything if I know how to solve the question above. Unfortunately I cannot change the whole naming system because I depend on the system and the other people in the project (I really would like to!). – Tall83 Apr 01 '17 at 03:11
  • 1
    Could you give a concrete example, please? – Ry- Apr 01 '17 at 03:54

1 Answers1

0

You can check for null, NaN etc like:

if(myVariable) {
    doSomething()
} else {
    doSomething()
}

it means, will be false if value is null, undefined, NaN, empty string(""), 0, false

You can save 90% time