# ? Operator

Could someone explain to me what this line of code means:

function1(num) ? 13 : 12;

I think it means

if function1(num) = 12 then function1(num) = 12

What is your input?

That code is incomplete because it isn’t doing anything with the value so with just that it would be equivalent to

``````if (function1(num)) 13;
else 12;
``````

In order to actually do something with the numbers you’d need to assign the whole thing to something for example:

``````x = function1(num) ? 13 : 12;
``````

which is the same as

``````if (function1(num)) x = 13;
else x = 12;
``````

You could easiy test it for yourself by picking two different values for num where one causes function1() to return true and the other has it return false.

x = function1(num) ? 13 : 12;

So some values:
if function1(num) =13
x=12

if function1(num) = 12
x = 12

if function1(num) = 5
x = 5

if function1(num) = 15
x = 15

if function1(num) = n
x = n unless n=13 then x=12

This is just ternary operator.

If num is TRUE or 1 assign 13 else assign 12
It is the simplified version of if and else.

Just the basic.

It all depends on what is in function1.

If function 1 is defined as:

``````function1 = function(num) {return isFinite(num);};
``````

then

``````x = function1(num) ? 13 : 12;
``````

would set x to 13 if num contains a finite number and to 12 if it contains infinity or something other than a number.

If function 1 is defined as:

``````function1 = function(num) {return false;};
``````

then it would set x to 12 regardless of what is in num.

You haven’t showed us your function1() so what num needs to be to return true (and so set a value of 13) and what it needs to be to return false (and set a value of 12) are completely unknown to us.

If function 1 is defined as:

``````function1 = function(num) {return 12===num ? true : false;};
``````

then

``````x = function1(num) ? 13 : 12;
``````

would set x to 13 if num is 12 and set x to 12 if num is anything at all except 12.

First understand that the comparison operator is == not =, otherwise you’ll soon be back asking another question.

I still don’t think you understand:

The statement

``````function1(num) ? 13 : 12;
``````

evaluates to 13 when function1(num) returns a non-zero value, otherwise 12.

Or more accurately, when function1(num) returns a non-falsy value, then the above code evaluates to 13.
If function1(num) is a falsy value (false, undefined, null, NaN, 0, “”), then the above code evaluates to 12.

The question mark is a conditional operator.
condition ? expr1 : expr2

You can see that above link for further details.