Dude Alex
Dude Alex

Reputation: 83

Can somebody explain this javascript statement to me?

I am working on a project which needs a lot of javascript coding. And I'm new to Javascript.

Just found a code but can't understand. Can somebody explain to me? I tried to search for answers but turn out with no result.

var keyCode = (e.keyCode ? e.keyCode : e.which);

I just wanna know what '?' and ':' mean in the above code. And is there any alternative way to write it?

Thanks a lot.

Upvotes: -1

Views: 66

Answers (3)

geoff
geoff

Reputation: 2276

The syntax you see is called a ternary operator. It is often used when an if... else... statement may be unnecessary, or too long. You will see it a lot in conditional variable assignments like the one above.

Basically, the syntax is like this:

([condition to test] ? [what should we do if true] : [what should we do if false]).

It is shorthand for

if([condition to test]) {
    [what should we do if true];
}
else {
    [what should we do if false];
}

In that example, we are trying to assign var keyCode. Since some browsers use e.which to pass in the numeral value of the key pressed, we have to account for both e.keyCode or e.which, and assign the appropriate value.

Also important to note: e.keyCode is not necessarily a boolean value. However, in JavaScript, any variable can be interpreted as boolean. e.keyCode has boolean value false if it's not defined.

Upvotes: 4

Rayan Bouajram
Rayan Bouajram

Reputation: 743

It's a shorthand for if/else.

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

Upvotes: 1

RoverMAX
RoverMAX

Reputation: 89

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

Upvotes: 1

Related Questions