function SortByID(x,y) {
return x.id - y.id;
}
function SortByName(x,y) {
return ((x.Name == y.Name) ? 0 : ((x.Name > y.Name)? 1: -1));
}
I am new to Javascript and I am learning how to make a sorting algorithm. I have a few questions regarding the two functions above.
1.Can you please explain the line of code below to me in words?
return ((x.Name == y.Name) ? 0 : ((x.Name > y.Name)? 1: -1));
2.What does the question mark in the above code mean?
3.what doest the "? 1: -1" and "? 0 :" means?
Many Thanks!
You are looking at a ternary operator. It's a short way of writing if else statements.
((x.Name == y.Name) ? 0 : ((x.Name > y.Name)? 1: -1));
Is the same thing as.
if ( x.Name == y.Name ) {
return 0;
} else {
if ( x.Name > y.Name ) {
return 1;
} else {
return -1;
}
}
Another way to read it would be like this.
(( Condition ) [IF TRUE] 0 [IF FALSE] (( Condition ) [IF TRUE] 1 [IF FALSE] -1 ));
The question mark is known as the conditional operator (or ternary operator) it is a shorthand way of an if then else block, bearing this in mind we have:
1.Can you please explain the line of code below to me in words?
If x.Name equals y.Name return 0 otherwise if x.Name is greater than y.Name return 1 otherwise return -1
2.What does the question mark in the above code mean?
The '?' operator takes the form:
(expression evaluating to true / false) ? (if true expression) : (if false expression)
3.what doest the "? 1: -1" and "? 0 :" means?
See answer 2 for syntactic meaning. In this context returning 0 means the values are deemed equal, -1 means the first value is less than the second and 1 means that the first value is greater than the second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With