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();    
updateNews();
sourceSelector.value = defaultSource;  
sourceSelector.addEventListener('change', e => {
updateNews(e.target.value);
});
});

Now I have the news sources update function:

async function updateNewsSources() {
const response = await fetch(`https://newsapi.org/v2/sources?apiKey=${apiKey}`);
const json = await response.json();
sourceSelector.innerHTML =
json.sources.map
(source =>`<option value="${source.id}">${source.name}</option>`)
.join('/n');
 }

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>"})()
.join('/n');
 }

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 _
Al

an arrow function:

 e => {
updateNews(e.target.value);
}

is functionally equivalent to writing:

 function (e) {
updateNews(e.target.value);
}

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 => {
updateNews(e.target.value);
});

as:

sourceSelector.addEventListener('change', updateNewsCall);
...
function updateNewsCall(e) {
updateNews(e.target.value);
}

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.

2 Likes

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="${source.id}">${source.name}</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 -
Al

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.