0

I want to know about what exactly is being done with variable a in below function :

function c(a) {
    var b = new Date;
    return Math.round(b.getTime() / 1e3 + (a ? a : 0))
}

Code that needs clarity:

(a?a:0)

Just want to know what is the logic of highlighted text.

Rajesh
  • 24,354
  • 5
  • 48
  • 79
praveen
  • 3
  • 3
  • 2
    It is a ternary operator... if a is a truthy value then use that else pass 0 – Arun P Johny Jan 25 '16 at 07:55
  • it's a rough way of making `a == 0` if null/false/undefined (falsey) passed in to function c ... may as well have been `(a || 0)` – Jaromanda X Jan 25 '16 at 07:55
  • Duplicate of http://stackoverflow.com/questions/1771786/question-mark-in-javascript. There is more than enough documentation on that pattern already. – Frederik.L Jan 25 '16 at 08:02

5 Answers5

1

If a is undefined or false or null or NaN it will return 0 else it will return value of a

Lets assume

var someVar = 23;

function c(a) {
    return a ? a : 0;  //Also true for negative values
}

c(someVar); //will return 23

And

 var someVar = -22;        
 c(someVar); //will return -22

And

 var someVar = false;        
 c(someVar); //will return 0

And

 var someVar;  //someVar is undefined       
 c(someVar); //will return 0
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
1

You probably wanted to use bold style, aren't you?

The statement x > 5 ? true : false is a shortened version of an if...else statement. You put the statement before the "?". The ":" separates the if and else part. If the statement is true, then the part before the : fires, if false, then the one after it. Because javascript likes to convert anything into booleans, the statement you have is the same as if (a > 0) { b = a } else { b = 0} If you want to know more about these statements, search for ternary operators

Bálint
  • 4,009
  • 2
  • 16
  • 27
1

these two lines

var b = new Date;
return Math.round(b.getTime() / 1e3 + (a ? a : 0))

can also be written as (for better readability)

var b = new Date;
var c = b.getTime() / 1e3 ; // 1e3 is 1000, so c is basically number of seconds since 1970

if ( !a ) //if a is either undefined, null or false
{
  a = 0;
}
return Math.round(c+a); //now c+a is adding these seconds to the paramter you have passed

So this function is basically passing the number of seconds since 1970 to the value you are passing.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

the "? : " is known as a ternary operator. It is a shortcut for an if else. For example, var b = a ? a : 0 is equivalent to:

var b;
if(a){ 
   b = a;
}else{ 
   b = 0; 
}  

Also, for the sake of clarity, your code misses () and ;. Here is a correct version:

function c(a) {
    var b = new Date();
    return Math.round(b.getTime() / 1e3 + (a ? a : 0));
}

Have a look at this question for further explanation.

Community
  • 1
  • 1
Derlin
  • 9,572
  • 2
  • 32
  • 53
0
if(a){
   return a;
}
else{
   return 0;
}
gdreamlend
  • 108
  • 9