Improving code length and readability by replacing if-cases with lookup tables

Submitted by Peter Majmesku on Wed, 12/27/2017 - 14:32

The following example shows via JavaScript, how a long function with if-cases can be shortened and made more readable by a lookup table.

function doSomething(a) { 
  if (
=== 'x') { 
    
doX(); 
  } else if (
=== 'y') { 
    
doY(); 
  } else { 
    
doZ(); 
  } 
}  

Will become this:

function doSomething(a) { 
  var 
lookup = { xdoXydoY }, def doZ
  
lookup[a] ? lookup[a]() : def();

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.