1

So I stumbled on some Javascript timer example and there was this function, which gets a number into it and then the function returns the time:

function timer(variable){
   return variable > 9 ? variable : "0" + variable;
}

And the whole code would look something like this:

var sec = 0;
function timer(variable){
    return variable > 9 ? variable : "0" + variable;
}
setInterval(function(){
    $("#time-id").val("Minutes: "+timer(parseInt(sec/60, 10))+" Seconds: "+timer(++sec%60));
}, 1000);

So yes, the setInterval function is pretty clear to me but about the timer().

What is the usage of ? in it? And how does it understand if I have multiple params given to it. Should it not be marked like this : timer(variable1, variable2){} ?

gromiczek
  • 2,608
  • 4
  • 24
  • 46
Veske
  • 527
  • 1
  • 3
  • 15
  • 3
    that's called a ternary operator. see : http://msdn.microsoft.com/en-us/library/ie/be21c7hw(v=vs.94).aspx – Timothy Groote Apr 18 '14 at 13:13
  • In your example there aren't any "multiple params" to understand. – Thomas Urban Apr 18 '14 at 13:16
  • Technically, it's called the [conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator); people sometimes refer to it as the ternary operator because it's the only ternary (three-argument) operator in most languages and many books call it the "ternary ?:" operator -- which should be read as "ternary conditional operator". – Russell Zahniser Apr 18 '14 at 13:16
  • Well timer(parseInt(sec/60, 10)) is sending in two params ? – Veske Apr 18 '14 at 13:16
  • 1
    No, `parseInt` returns one value and that value is sent in for the param. – Russell Zahniser Apr 18 '14 at 13:17

4 Answers4

5

Timer is formatting time so that if it is 6:05, it shows up as 6:05 and not 6:5

return variable > 9 ? variable : "0" + variable;

is the same as

if ( variable > 9 ) {
    return variable
} else {
    return "0" + variable
}
bottens
  • 3,438
  • 1
  • 11
  • 14
4

?: is an operator shared by a lot of modern languages. It's a shortcut for an if test. The structure is as follows :

condition ? resultIfTrue : resultIfFalse

In your case, it appends a 0 to your variable if the variable is < 10. You could read it as :

if (variable > 9)
     do nothing
else
     add a "0" before
Chris Wesseling
  • 5,012
  • 2
  • 27
  • 64
Aserre
  • 4,397
  • 3
  • 30
  • 51
2

It's saying that if variable is 10 or more, it just echoes back variable; otherwise it adds a 0 on the start to still make it two digits.

Russell Zahniser
  • 15,480
  • 35
  • 29
2

variable > 9 ? variable : "0" + variable; is a ternary expression. variable > 9 is evaluated, and if it's truthy, variable is returned, otherwise "0" + variable is returned. Think of it as a one-liner substitute for an if-else statement with assignment.

Bucket
  • 6,877
  • 9
  • 30
  • 41