Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this syntax mean: ? event.charCode : event.keyCode; [closed]

Tags:

javascript

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;
like image 323
Damien Golding Avatar asked Apr 17 '26 23:04

Damien Golding


2 Answers

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;
}
like image 86
Blender Avatar answered Apr 20 '26 13:04

Blender


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

like image 41
NullPoiиteя Avatar answered Apr 20 '26 12:04

NullPoiиteя



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!