What to do if variables are undefined AND you are using an IF statement

I came across a request where we only wanted to execute a Javascript function if variables were equal to certain values. The challenge I had occured when the values I was checking were undefined.

In my example I had conditions to my IF statement and was using AND criteria within each condition. What I found was that neither worked if the variables I was checking or were coming back undefined.

I changed my code by including an IF statement that first checked if there variables were defined before completing the IF statement. If they weren’t defined the second

Preliminary JS that did not always work because the variable could be undefined:

if ((a == 317 && publication == ‘test’ ) || (! b.includes(“312”) && publication != ‘test’ )) {
console.log(“hello world variables defined”)
}
else
{
console.log (‘hello world even if variables are not defined ‘)
}

Updated JS that did work regardless of if the variable was defined:

if (a !== undefined || b !== undefined) {

if ((a == 317 && publication == ‘test’ ) || (! b.includes(“312”) && publication != ‘test’ )) {
console.log(“hello world variables defined”)
}
}
else
{
console.log (‘hello world even if variables are not defined ‘)
}