skip to Main Content

This isn’t a problem, more of a curiosity. I have an anonymous arrow function that writes data to the screen.

const output = (message, selector, html=false) => {
  if (html) {
    selector.innerHTML += message;
  } else {
    selector.textContent += message;
  }
};

Pretty straightforward and easy to implement and use. It isn’t too long, but I am curious if I can make a one line function; essentially collapsing the if the else statement into a ternary.

Something like this:

const output = (message, selector, html=false) => selector.(html?innerHTML:textContent) = message;

Again, my current function works flawlessly and this is more of a curiosity.

The above example has been tried and failed. Additionally I tried the following, which failed, as I knew it would.

const output = (message, selector, html=false) => selector.${(html?innerHTML:textContent)} = message;

2

Answers


  1. I think you’re looking for this:

    const output = (message, selector, html=false) => {
      selector[html ? 'innerHTML' : 'textContent'] += message;
    };
    
    Login or Signup to reply.
  2. You can make it one liner with simply doing this:

    const output = (message, selector, html=false) => selector[html ? 'innerHTML' : 'textContent'] += message;
    

    But it doesn’t give more readability to your code.

    I would suggest to use guard clause like this

    const output = (message, selector, html = false) => {
      if (html) return (selector.innerHTML += message);
      selector.textContent += message;
    };
    

    Have some more reading at:

    1. https://learningactors.com/javascript-guard-clauses-how-you-can-refactor-conditional-logic/

    2. https://medium.com/@timothydan/javascript-guard-clauses-64b999e3240

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search