0

I have the following code and I am trying to understand it:

labels: {
   formatter: function () {
    return (this.value > 0 ? ' + ' : '') + this.value + '%';
                        }
        },

But I don't understand what does ? means? Could anyone explain me? I would appreciate it.

kaka
  • 129
  • 2
  • 13
  • 6
    that is called ternary operation. its just like if/else. – Jai Jun 01 '15 at 12:57
  • possible duplicate of [JS How to use the ?: (ternary) operator](http://stackoverflow.com/questions/6259982/js-how-to-use-the-ternary-operator) – Adrian Wragg Jun 01 '15 at 12:58

5 Answers5

5

The ? is the conditional ternary operator, you can express the same with an if statement like this:

labels: {
    formatter: function () {
        if (this.value > 0) {
            return ' + ' + this.value + '%';
        } else {
            return '' + this.value + '%';
        }
    }
},

It works like: If the condition is true, execute the first argument, if not the second.

CONDITION ? EXPRESSION_ON_TRUE : EXPRESSION_ON_FALSE

Some other examples how this operator can be used:

// assign 'a' or 'b' to myVariable depending on the condition
var myVariable = condition ? 'a' : 'b';

// call functionA or functionB depending on the condition
condition ? functionA() : functionB();

// you can also chain them (but keep in mind this can become very complicated)
var myVariable = cond ? (condA ? 'a' : 'b') : (condB ? 'c' : 'd')

Also, this operator is nothing special that you can only use with the jQuery library, you can also use it with plain JavaScript.

tbraun89
  • 2,196
  • 3
  • 26
  • 43
1

The converted if else statement would be:

if(this.value>0)
    return '+' + this.value + '%';
else
    return '' + this.value + '%';
Guruprasad J Rao
  • 28,253
  • 13
  • 87
  • 176
0

This is called ternary operation:

condition if ' + ' else '';
//-------^?^-------^-:-^

so in ternary operation ? is if and : is else.


Note:

Your question: What is ? in JQUERY.

This is not jQuery but just native javascript which uses ternary operation, which is available to use in any js lib. So it's not a part of jQuery but javascript. jQuery is built on top of javascript so it can use it because it is still javascript.

In fact i would say that jQuery is the simplified javascript library.

Community
  • 1
  • 1
Jai
  • 71,335
  • 12
  • 70
  • 93
0

Basically it means, if this.value is bigger than 0 then '+' else ' '

LVDM
  • 434
  • 2
  • 20
0

It's a ternary operator:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

It's a quick if statement. If this.value is greater then zero, then the value used is ' + ', otherwise the value is ''.

So if 1 is passed in, the return will be ' + 1 %', if zero is passed in the return will be '0 %', and if -1 is passed in the value will be ' -1 %'.

Brian
  • 2,916
  • 3
  • 27
  • 41