DEV Community

Discussion on: How would you refactor this JS function?

Collapse
 
cicirello profile image
Vincent A. Cicirello • Edited

I didn't read through all of the other comments so someone else may have already suggested this one, but if the objective is to minimize conditions that are explicitly checked, start with the last case like this:

const lineChecker = (line, isFirstLine) => {
  if (line === "") {
    return "<br />";
  } else if (!line) {
    return ``;
  } else if (isFirstLine) {
    return `<h1>${line}</h1>`;
  } else {
    return `<p>${line}</p>`;
  } 
};
Enter fullscreen mode Exit fullscreen mode

I also got rid of the concats with the unnecessary local variable.

Collapse
 
jamesthomson profile image
James Thomson

When using the early return method, you don't need else if. Just use if.