Use a named function to replace an arrow function

Within my html is a select with an id of ‘newsSources’. I then have some starter variables:

const apiKey = 'xxxxxxxxxxxetc';
const main = document.querySelector('main');
const sourceSelector = document.querySelector("#newsSources");
const defaultSource = 'bbc-news';

Now I have calls for functions which will define the news sources and news updates:

window.addEventListener('load', async e => {
await updateNewsSources();    
sourceSelector.value = defaultSource;  
sourceSelector.addEventListener('change', e => {

Now I have the news sources update function:

async function updateNewsSources() {
const response = await fetch(`${apiKey}`);
const json = await response.json();
sourceSelector.innerHTML =
(source =>`<option value="${}">${}</option>`)

Now this all works for delivering and updating the new sources select dropdown. However,
I wanted to see if the arrow function above could be replaced with a named function.
One great member sent me this:

(function myFunction(id, name){
 "<option value=" + id + ">" + name + "</option>"})()

Unfortunately, when I replaced the arrow function line with the named function above there was no render ie the select was not functioning. I have fiddled with brackets etc but it is beyond me.
Is it possible to replace the arrow function above with a self invoking function?

Thanks _

an arrow function:

 e => {

is functionally equivalent to writing:

 function (e) {

in the same space.

If you wish to move the function declaration out of the inline call, give it a name, then you could write:

sourceSelector.addEventListener('change', e => {


sourceSelector.addEventListener('change', updateNewsCall);
function updateNewsCall(e) {

The general purpose of anonymous (or lambda) functions is for function code that you’re not going to use more than once; a throwaway function.


In this case, agreed.

Nonetheless, it is worth mentioning that there are a few small differences between regular functions and arrow functions. For example, arrow functions have no this binding, which can often be an advantage with things like setTimeout.

Hi - thanks for your response…it works. However, it was this:

(source =><option value="${}">${}</option>)

that I was concerned about. Is it possible to code this without using the arrow function format?

I tried to use your response ie function(source) {…etc but no luck, the select doesn’t function.

Thanks -

You will need to include a return in front of the backtick in that line. It’s using the abbreviated syntax.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.