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.
This gives to
abc
the value ofdef
if it isn't falsy (i.e. notfalse
,null
,undefined
,0
or an empty string), or the value ofghi
if not.This is equivalent to:
This is commonly used for options:
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
The code var
abc = def || ghi;
is the same thing as
You want a condition like an if statement?
which as written as a ternary operator is:
Yes, you can add condition to variable declaration
You can use it like this,
jsfiddle demo
OKay, see, it is something like, you either check if one is true. The true one will be returned. :)
Is equivalent to: