[ACCEPTED]-javascript var charCode = (evt.which) ? evt.which : event.keyCode;-javascript

Accepted answer
Score: 10

It's called the ternary conditional operator. It's basically short for 9 an if...else:

var charCode;
if(evt.which) {
    charCode = evt.which;
}
else {
    charCode = evt.keyCode;
}

Basically, it evaluates the first operand. If 8 that evaluation returns true, the second operand 7 is returned. If false, the third is returned.

As 6 for whether you can use it in other languages, you 5 often can. From the languages you listed, Java 4 and PHP both have it, and I'd be very surprised 3 if C++ didn't (edit - a quick Google reveals 2 that C and C++ do indeed support it too). For 1 more, see Wikipedia.

Score: 2

First, of all, var charCode = starts assignment to local 7 charCode variable. Next, ternary operator is used. It compounds 6 of three parts, condition, what happens 5 if it's true and what happens if it's false.

(evt.which) ? evt.which : event.keyCode
# condition # if true   # if false

In 4 this case, it's used for feature detection 3 (keyboard key event). evt.which is proper way to 2 do it, but in very old browsers you may 1 want to use event.keyCode.

Score: 2

Others correctly pointed out that it is 1 shorthand for:

var charCode;
if(evt.which) {
    charCode = evt.which;
}
else {
    charCode = evt.keyCode;
}

but it is also longhand for:

var charCode = evt.which || evt.keyCode;
Score: 1

This is called the conditional operator.

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

To 5 the left of the ? is the condition. To the 4 right are to results seperated by a :. If 3 the condition is true, the result on the 2 left of the colon is used, otherwise the 1 it's the result on the right.

More Related questions