0

What is the meaning of this condition in java script?
How does it work?

function displayunicode(e){
    var unicode = e.keyCode ? e.keyCode : e.charCode
    alert(unicode)
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Ohad
  • 1,563
  • 2
  • 20
  • 44

3 Answers3

4

Shorthand for:

var unicode;
if (e.keyCode)
   unicode = e.keyCode
else
   unicode = e.charCode

alert(unicode);

You can even write it as:

var unicode = e.keyCode || e.charCode;
NG.
  • 22,560
  • 5
  • 55
  • 61
2

in keypress event in javascript you have this stuff, in some browsers you just have the e.keyCode in your event object, which here is e, and in some other browsers you have e.charCode instead. both keyCode and charCode refers to the key which is pressed.

and as @SB. has pointed out:

e.keyCode ? e.keyCode : e.charCode

means exactly:

var unicode;
if (e.keyCode)
    unicode = e.keyCode
else
    unicode = e.charCode

and as I have said this piece of code wants to get the key which has been pressed in keypress event.

Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
  • I think you have voted up, there is a sign below my votes part that you have to push if it is the answer, you were looking for – Mehran Hatami Dec 25 '13 at 21:01
0

It is just a simple inline if, have a look at this to understand how it works: How to write an inline IF statement in JavaScript?

Community
  • 1
  • 1
Christian Giupponi
  • 7,408
  • 11
  • 68
  • 113