I am quite new to JavaScript, and so am still coming into small things that I don't quite understand and don't seem to appear when I search for them. Please could somebody point me out what the ? : syntax is doing below.
var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
This is called the ternary operator. It's a short if...else statement.
Basically, your code can be expanded to this.
var chCode;
if ('charCode' in event) {
chCode = event.charCode;
} else {
chCode = event.keyCode;
}
its the ternary operator
The ?: operator can be used as a shortcut for an if...else statement. It is typically used as part of a larger expression where an if...else statement would be awkward.
var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
same as
var chCode;
if ('charCode' in event) {
chCode = event.charCode;
} else {
chCode = event.keyCode;
}
test ? expression1 : expression2
expression1 =An expression returned if test is true
expression2 = when false
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