How to Check If Key Press (event.key) is a Number in JavaScript

After checking for a keypress event, suppose we want to check if the pressed key is a number 0-9.

We can use isFinite() on event.key, which will check if event.key is a finite number.

const getCode = (e) => {
  e = e || window.event;
  return e.key;
const handleKeyPress = (e) => {
  const key = getCode(e);
  if (isFinite(key)) {
    console.log(`Number ${key} was pressed!`);
document.addEventListener("keypress", handleKeyPress);