0

to get information about what key was pressed, I now use following code:

function AddEventListeners() {
    document.getElementById('txtHangman').addEventListener('keypress', TextHangman.bind(this), false);
}

And then the eventhandler function:

function TextHangman(_key) {
    var _keypressed = _key.which || _key.key;
}

The code works and gives me the information I want but I don't understand what the || operator does when initiliazing the var _keypressed. Some explanation would be great.

Thanks!

G

GST
  • 5
  • 3

3 Answers3

1

It means the same as it does everywhere else. It does nothing special when used near a var statement.

If the left hand side evaluates as true (i.e. not 0, undefined, etc), it evaluates as the left hand side.

Otherwise, it evaluates as the right hand side.


Precedence rules means it gets resolved before the assignment.


Essentially the code is the same as:

if (_key.which) {
    var _keypressed = _key.which;
} else {
    var _keypressed = _key.key;
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • The list of falsy values are available at https://developer.mozilla.org/en-US/docs/Glossary/Falsy – Patrick May 02 '15 at 09:01
0

This means when there is any falsy value like null or undefined or 0 in _key.which then it should be initialized with _key.key.

You can see it as shortcut for:

var _keypressed = _key.which;
if (!_keypressed) {
    _keypressed = _key.key;
}
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
0

It provides a fallback to the var. If the first option is false, null or undefined, the var will be set with the second value

Daniel Ortiz
  • 901
  • 2
  • 7
  • 14