0

I have an if statement, which ideally I'd like to check the value of a variable, only if THAT variable exists. This is not just checking whether a variable exists (e.g. by using typeof()), but preventing an attempt to check what the value of the variable is if it doesn't exist. My if statement looks something like this:

variable_1 = "I am now being defined";
// in an instance where value_2 has not been defined
if(  variable_1 == "value_1" & 
     variable_2 == "value_2"){
   // code to execute
} 

however, sometimes variable_2 won't have been defined, and so I get the error "variable_2 is not defined". Is there an elegant way to check if variable_2 exists, and if it does exist check what its value is?

Thanks is advance! Apologies if I've overlooked something basic.

  • 2
    `however, sometimes variable_2 won't have been defined, and so the code crashes when that happens` how? – gurvinder372 Sep 21 '17 at 12:00
  • `Is there an elegant way to check if variable_2 exists, and if it does exist check what its value is?` check `typeof variable_2 != "undefined"` – gurvinder372 Sep 21 '17 at 12:01
  • Btw, your syntax is not correct at `&` it should be `&&` – Jigar Shah Sep 21 '17 at 12:01
  • 1
    `if (variable_2 !== undefined && …)`, start your `if` with this. When the variable hasn't been defined as yet your `if` will no longer crash. – Thijs Sep 21 '17 at 12:02
  • gurvinder372: I get an error like: Uncaught ReferenceError: variable_2 is not defined –  Sep 21 '17 at 12:02
  • @AnthonyHaffey Please show the exact code you have tried... – gurvinder372 Sep 21 '17 at 12:05
  • @gurvinder372 I've adjusted the exemplar code to replicate the error. When I've implemented Thijs's answer I don't get an error. So using this solution, I need to write: variable_1 = "I am now being defined"; if( variable_1 == "value_1" & typeof(variable_2) !== "undefined" && variable_2 == "value_2"){ // code to execute } And I won't get an error, even though variable_2 is undefined –  Sep 21 '17 at 12:14

0 Answers0