Handling arrow keys and tabIndex I'm wondering how to "beautify"/"simplify" this code:

function handleKeyDown (e) {
  if (e.key === 'Enter') {
    e.preventDefault()
    myCustomEvent(e)
    return
  }
  if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
    e.preventDefault()
    e.key === 'ArrowDown'
      ? document &amp;&amp;
        document.activeElement &amp;&amp;
        document.activeElement.nextElementSibling &amp;&amp;
        document.activeElement.nextElementSibling.focus()
      : document &amp;&amp;
        document.activeElement &amp;&amp;
        document.activeElement.previousElementSibling &amp;&amp;
        document.activeElement.previousElementSibling.focus()
  }
}


It seems too verbose to me. Is there something I'm doing wrong? How can I write it better?
Through clever usage of destructuring and using objects to store possible events, you can do this.
function focus(key){
  const {activeElement:{[key]: elementSibling} = {}} = document;
  if(elementSibling){
    elementSibling.focus();
  }
}

const ACTIONS = {
  ArrowDown: () =&gt; focus('nextElementSibling'),
  ArrowUp: () =&gt; focus('previousElementSibling'),
  Enter: (e) =&gt; myCustomEvent(e)
}

function handleKeyDown (e) {
  const handler = ACTIONS[e.key];
  if(handler) {
    e.preventDefault();
    handler(e);
  }
}

Here is a working example:


function focus(key){
  const {activeElement:{[key]: elementSibling} = {}} = document;
  if(elementSibling){
    elementSibling.focus();
  }
}

const ACTIONS = {
  ArrowDown: () =&gt; focus('nextElementSibling'),
  ArrowUp: () =&gt; focus('previousElementSibling'),
  Enter: (e) =&gt; myCustomEvent(e)
}

function handleKeyDown (e) {
  console.log(e.key, e.target);
  const handler = ACTIONS[e.key];
  if(handler) {
    e.preventDefault();
    handler(e);
  }
}

// simulating an event
window.addEventListener('keyup', handleKeyDown);
&lt;h3&gt;Click on an element then press ArrowUp or ArrowDown&lt;/h3&gt;
&lt;input type="text"/&gt;
&lt;input type="text"/&gt;
&lt;input type="text"/&gt;
&lt;input type="text"/&gt;