10

This doesn't make sense to me, but I have a feeling I saw a code using this:

var abc = def || ghi;

My question is, is this valid? Can we add a condition to a variable declaration? I imagine the answer is no but I have this at the back of my mind that I saw something similar in code once.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Kayote
  • 14,579
  • 25
  • 85
  • 144

4 Answers4

17

This gives to abc the value of def if it isn't falsy (i.e. not false, null, undefined, 0 or an empty string), or the value of ghi if not.

This is equivalent to:

var abc;
if (def) abc = def;
else abc = ghi;

This is commonly used for options:

function myfunc (opts) {
    var mything = opts.mything || "aaa";
}

If you call myfunc({mything:"bbb"}) it uses the value you give. It uses "aaa" if you provide nothing.

In this case, in order to let the caller wholly skip the parameter, we could also have started the function with

opts = opts || {};
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • +1. It might be more accurate to say if "`def` evaluates to true", since if it is `0`, the empty string, `false` etc. then `abc` will get the value of `ghi`. – James Allardice Jun 28 '12 at 18:10
6

The code var abc = def || ghi;

is the same thing as

if (def) { //where def is a truthy value
   var abc = def;
} else {
   abc = ghi;
}

You want a condition like an if statement?

if (xxx==="apple") { 
    var abc = def;
} else {
    abc = ghi;
}

which as written as a ternary operator is:

var abc = (xxx==="apple") ? def : ghi;
epascarello
  • 204,599
  • 20
  • 195
  • 236
3

Yes, you can add condition to variable declaration

You can use it like this,

function greet(person) {
    var name = person || 'anonymouse';
    alert('Hello ' + name);
}
greet('jashwant');
greet();​

jsfiddle demo

Jashwant
  • 28,410
  • 16
  • 70
  • 105
0

OKay, see, it is something like, you either check if one is true. The true one will be returned. :)

var abc = def || ghi;

Is equivalent to:

var abc = return (def == true) or (ghi == true)
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • 3
    Careful. Your answer implies that this operation always assigns a boolean value. This is **only** the case if `def` and `ghi` are boolean values. In all cases, `abc` will assume the value of `ghi` (whatever that value is) _unless `def` evalutes to true_. If `def` is "hello", then abc will be "hello" (not booelan). If `def` is false/empty/zero/undefined/etc., and `ghi` is "world", then `abc` will be "world" (again, not boolean). – quietmint Aug 27 '12 at 18:29