First of all, the simplest way to initialize loggedIn is by simply assigning it the return value of hasClass, which is a boolean:
var loggedin = $('body').hasClass('loggedin');
What you remember is a short way to provide default value for variables, by using the logical OR operator which returns the first value which evaluates to true or the last value if all are false:
jamie = jamie || 'or maybe not'; // identical to if (!jamie) jamie = 'or maybe not';
Finally, the || operator fails in certain edge cases where the initial value of the variable is falsy:
function f(number) {
number = number || 10; // if number is not provided, default to 10
console.log(number);
}
f(0) // whoops, number was provided, but it will log 10 instead.
In such cases (usually happens when you want to check only against null
and undefined
), not all falsy values, you can use the conditional operator:
number = number != null ? number : 10;
It's slightly more verbose, but still quite an elegant way to provide defaults.