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
I think you’re looking for this:
You can make it one liner with simply doing this:
But it doesn’t give more readability to your code.
I would suggest to use guard clause like this
Have some more reading at:
https://learningactors.com/javascript-guard-clauses-how-you-can-refactor-conditional-logic/
https://medium.com/@timothydan/javascript-guard-clauses-64b999e3240