Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript syntax Help on sorting function

Tags:

javascript

Code

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));
}

Problem Description

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!

like image 439
Chris Yeung Avatar asked Mar 27 '26 01:03

Chris Yeung


2 Answers

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 ));
like image 189
Seth Avatar answered Mar 29 '26 15:03

Seth


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.

like image 25
Rich O'Kelly Avatar answered Mar 29 '26 13:03

Rich O'Kelly