What is the JavaScript interrogation for? [duplicate]

Posted on

Question :

Citing an example:

         if(this.gap > 1 || !this.sorted)
         {
            this.sorted = true;
            this.gap = parseInt(this.gap / 1.3) == 0 ? 1 : parseInt(this.gap / 1.3);
            setTimeout(this.name + '.comb_sort_acending_order(0);', this.speed);
         }

This question mark ( ? ) means what?

    

Answer :

It is a conditional operator .

Do developers.mozilla.org :

  

Conditional operator

  
  

The conditional operator is the only JavaScript operator that uses three
  operands. The operator can have one of two values based on a
  condition. The syntax is:

condicao ? valor1 : valor2

  

If condition is true, the operator will have value1. Case
  otherwise, it will have the value of value2. You can use the
  conditional anywhere you would use a standard operator. For example:

var status = (idade >= 18) ? "adulto" : "menor";

In case of your example, if parseInt(this.gap / 1.3) == 0 then this.gap will be 1, otherwise parseInt(this.gap / 1.3) .

    

Leave a Reply

Your email address will not be published. Required fields are marked *