Is there a way to console log/error and return from a function in one line using ES6 syntax?

15 views Asked by At

I find myself writing code akin to the following quite a bit:

const fileEl = document.getElementById("import-style-file-input");
if (fileEl === null) {
   console.error("No file element");
   return;
}

Is there a way I could condense lines 3 & 4 into a single line? E.g.

if (fileEl === null) log_and_return("No file element");

Or do scope limitations make this impossible?

1

There are 1 answers

0
David On BEST ANSWER

Since return; by itself just returns undefined anyway, you can return the result of console.error which is also undefined:

if (fileEl === null) return console.error("No file element");

Something like this may look strange to another reader, so in any team environment I'd recommend getting opinions from the team members. But on a purely technical level, it does what you're looking for.


If team members want it to look more intuitive, wrapping the same functionality in a custom-named function does the same thing:

if (fileEl === null) return log_and_return("No file element");

// elsewhere...
function log_and_return(msg) { console.error(msg); }