DEV Community

Discussion on: How would you refactor this JS function?

Collapse
 
nemesarial profile image
Mark Holtzhausen • Edited

I came up with two revisions. The first is what I would actually prefer because of its readability. The second was just for fun.

const lineCheck = (line, isFirstLine) => {
  if(line==='') return '<br />'
  if(isFirstLine) return `<h1>${line}</h1>`
  return `<p>${line}</p>`
}
Enter fullscreen mode Exit fullscreen mode

This is nice and readable -- and a trick I learned early on was to exit early if you have an simple condition that determines the outcome.

This one does the same, but more concise.

const lineCheckConcise = (line, isFirstLine)=>
  line !== ''
    ? (isFirstLine ? `<h1>${line}</h1>` :  `<p>${line}</p>`) 
    : '<br />'
Enter fullscreen mode Exit fullscreen mode

The parentheses are not necessary, but makes it more readable. Also, I broke this into multiple lines to avoid horizontal scroll, but this is actually a single line function.