Reputation: 425
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.
Upvotes: 0
Views: 114
Reputation: 2234
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 nest them (but keep in mind this can become difficult to read)
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.
Upvotes: 5
Reputation: 74738
This is called ternary operation:
condition if ' + ' else '';
//-------^?^-------^-:-^
so in ternary operation ?
is if
and :
is else.
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.
Upvotes: 0
Reputation: 29683
The converted if else
statement would be:
if(this.value>0)
return '+' + this.value + '%';
else
return '' + this.value + '%';
Upvotes: 1
Reputation: 3334
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 %'.
Upvotes: 0