← Back tothis vs that

key vs keyCode vs which

Written byPhuoc Nguyen
Category
DOM
Created
16 Jun, 2020
`key`, `keyCode` and `which` can be used to determine which key is pressed. Following is a sample code that handles the `keyPress` event of a text box.
It checks if user presses the Enter key whose key code is 13:
textBoxElement.addEventListener('keydown', function (e) {
if (e.keyCode === 13) {
// Do something ...
}
});

Difference

According to MDN documentations, both keyCode and which are deprecated and will be removed from the Web standards.
Apart from that, both properties are supported differently by browsers. Some browsers use `keyCode`, other use `which`.
It's common to see how they are normalized as following:
const key = 'which' in e ? e.which : e.keyCode;

// Or
const key = e.which || e.keyCode || 0;

Good practice

It's recommended to use the key property. The sample code above can be rewritten as
if (e.key === 'Enter') {
// Enter is pressed
}

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn