0

I've no doubt this is a duplication of a question, but I can't find the correct search terms.

I'd like a shorthand variable declaration that won't be defined if its false. I remember it looking something like this:

 var jamie = jamie : 'or maybe not';

If this makes it easier to understand, this is what I'm actually trying to achieve.

    if($('body').hasClass('loggedin')){
        var loggedin = true;
    }

Remember, I have no idea what it is.

Jamie Hutber
  • 26,790
  • 46
  • 179
  • 291
  • How can a variable be false during its assignment? Can you explain what it is that you're doing, or what it is that you want to do? – David Thomas Oct 21 '13 at 21:40
  • forget how badly the question is written :) heh good point though, i'll update now :) – Jamie Hutber Oct 21 '13 at 21:40
  • I don't see how your "what I'm actually trying to achieve" has any relation to the original question. – Matt Ball Oct 21 '13 at 21:44
  • @MattBall I can understand your confusion. But let be the first to tell you I was as confused as you to what the hell I was asking. The most important thing is we got there in the end. Also Matt, it does I'd like an IF in the original question :) – Jamie Hutber Oct 21 '13 at 21:45

4 Answers4

7
 var jamie = someVarThatCanBeUndefined || 'or maybe not';

You can use the above to do coalescing

Here is an answer with more details Is there a "null coalescing" operator in JavaScript?

If you wanted short hand notation for if

Try this instead:

boolCondition ? "OneStringForTrue" : "AnotherForFalse"

This is often called the

Conditional (Ternary) Operator (?:) (JavaScript)
Community
  • 1
  • 1
TGH
  • 38,769
  • 12
  • 102
  • 135
3
var jamie = jamie || 'or maybe not';

Simple as that.

Robbie Wxyz
  • 7,671
  • 2
  • 32
  • 47
1

hasClass already boolean:

var loggedin = $('body').hasClass('loggedin');
Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
1

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.

Tibos
  • 27,507
  • 4
  • 50
  • 64