1

I am trying to understand what the ? and the : are doing in this code, I see it a lot in code but I never can understand what exactly it is doing?

Could someone please point me in the right direction, this bit of code is from the jQuery validate() DOCS

$(".selector").validate({
  invalidHandler: function(event, validator) {
    // 'this' refers to the form
    var errors = validator.numberOfInvalids();
    if (errors) {
      var message = errors == 1
        ? 'You missed 1 field. It has been highlighted'
        : 'You missed ' + errors + ' fields. They have been highlighted';
      $("div.error span").html(message);
      $("div.error").show();
    } else {
      $("div.error").hide();
    }
  }
});
thechrishaddad
  • 5,726
  • 7
  • 24
  • 29

4 Answers4

5

The ? : isn't jquery, just vanilla javascript. It's called conditional (ternary) operator which can be used as shorthand for the standard if/else statement: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Conditional_%28ternary%29_operator

Basically it says

val = (boolean expression)? (val if boolean is true) : (val if boolean is false)

So in your case it's saying that message equals 'You missed 1 field. It has been highlighted' if errors == 1 is true, otherwise message equals 'You missed ' + errors + ' fields. They have been highlighted'.

winhowes
  • 6,741
  • 5
  • 27
  • 39
  • Okay so it basically is an alternative way of doing a check? similiar to if/else statements, my next question would be, why would you use this over a if/else statement? – thechrishaddad Jul 01 '15 at 02:18
  • 2
    Yeah, that's exactly it. You use it as a more shorthand way of assigning a value to a variable based on the if else condition. – winhowes Jul 01 '15 at 02:19
2

That is conditional (ternary) operator which is a shortcut for the standard if/else statement.
Here is an example to demonstrate:

var grade = 85;
console.log("You " + (grade > 50 ? "passed!" : "failed!"));

//Output: You passed!

/* The above statement is same as saying:
if(grade > 50){
    console.log("You " + "passed!");  //or simply "You passed!"
}
else{
    console.log("You " + "failed!"); 
}
*/
aleksandar
  • 2,293
  • 2
  • 11
  • 22
2

var errors = 1; 
// define `message` 
// if `errors == 1`
var message = errors == 1 
        // `errors == 1`
        ? 'You missed 1 field. It has been highlighted' 
         // `errors != 1`
        : 'You missed ' + errors + ' fields. They have been highlighted';
console.log(message)
guest271314
  • 1
  • 10
  • 82
  • 156
2

Conditional (ternary) Operator

The first part before the question mark is the expression you're trying to evaluate. The second part after the question mark and before the colon is the true-clause. The third part after the colon is the false-clause.

3abqari
  • 218
  • 1
  • 2
  • 10