# Check if js variable exists and checking it's value

I feel like this bit of code could be condensed or made better in some way. It may in fact not be but figured I'd get some people smarter then me to have a look. I have multiple pages on my site and in certain pages I'm setting a js variable:

var header_check = "user-profile";


Some pages I'm not setting that variable. In another js file that gets loaded on the page I check if that variable exists and perform various actions if it does. Is this the best way to check if the variable exists and also is this the best way to see if 'user-profile' is set? Any help is appreciated.

var header_cookie = typeof header_check !== 'undefined' ? 'user-profile' : 'admin-profile';

var city_profile = cookie_check ? 'userCity' : 'city';
var state_profile = cookie_check ? 'userState' : 'state';

-

First off, your code really breaks down to this logic and I find it helpful to write it out the longer version to full understand the logic flow before trying to shorten it:

var header_cookie, cookie_check, city_profile, state_profile;
if (typeof header_check !== "undefined") {
city_profile = 'userCity';
state_profile = 'userState';
} else {
city_profile = 'city';
state_profile = 'state;
}


FYI, I also find this a LOT easier to follow what's actually happening than the code you have. It also saves several comparisons on the cookie_check value.

There are some ways to shorten this, but it's not entirely clear that any are "better" where the definition of better includes readability by someone who has never seen this code before, but you can decide what you think of that issue for the alternatives:

Since you really only have two states, you could predefine each state and then just pick which one to use and access the properties off a single state object:

var userState = {
};
};


Done this way, you'd access state.header_cookie, state.city_profile and state.state_profile rather than your standalone variables.

Or, if you wanted to keep the individual variables, you could do this:

var states = {