Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you add a condition to a variable declaration?

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.

like image 338
Kayote Avatar asked Jun 28 '12 18:06

Kayote


People also ask

Can I put IF statement in a variable?

An if-then statement can be used to create a new variable for a selected subset of the observations. For each observation in the data set, SAS evaluates the expression following the if. When the expression is true, the statement following then is executed.

How do you declare a variable in a condition?

To declare a condition variable, use type cond_t. To initialize it, use function cond_init(). Note that all condition variable related names start with cond_. Function cond_init() takes three arguments.

What statements can be used to declare a variable?

You declare a variable to specify its name and characteristics. The declaration statement for variables is the Dim Statement. Its location and contents determine the variable's characteristics. For variable naming rules and considerations, see Declared Element Names.

Can we use in variable declaration in C?

Variable Declaration in C You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.


3 Answers

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 || {};
like image 101
Denys Séguret Avatar answered Oct 13 '22 02:10

Denys Séguret


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;
like image 40
epascarello Avatar answered Oct 13 '22 01:10

epascarello


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

like image 27
Jashwant Avatar answered Oct 13 '22 01:10

Jashwant