jalexyep jalexyep -4 years ago 67
Javascript Question

Can someone explain this line of code? 0 % 2

Was working through the following problem:


function
padIt
accept 2 parameters:

1.
str
, it's a string representing the string to pad, we need to pad some
"*"
at leftside or rightside of
str


2.
n
, it's a number, how many times to pad the string.


This is the answer:

function padIt(str,n){
var count = 0;
while ( count < n ) {
count % 2 ? str += '*' : str = '*' + str;
count ++
}
return str;
}


Can someone explain this part?
count % 2 ? str += '*' : str = '*' + str;


Say I put these parameters in the function,
padIt('a', 1)

The first loop will have
count = 0
so the function will have
0 % 2
which =
0
. Why does the function choose the option
str = '*' + str
to output
'*a'
? Why not
str += '*'
to output
'a*'
?

Answer Source

This is a one-line shorthand for an if-else statement. It's called the conditional(ternary) operator.

 function padIt(str,n){
  var count = 0;
  while ( count < n ) {
    count % 2 ? str += '*' : str = '*' + str;
    count ++
   }
    return str;
  }

This is construct count % 2 ? str += '*' : str = '*' + str; is the same as

      if(count % 2){
          str += '*';
       }else{

         str = '*' + str;
       }


count % 2 ? str += '*' : str = '*' + str; means if count is even do this if not do that.
The obvious advantage is that is it's shorter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download