Functions in JavaScript, are these the same?


#1

Hi,

I am trying to get my head around middleware in the intensive course, but am struggling with something fairly basic in one of the lessons. One of the first lessons has us refactoring a common logging task into a function for code-reuse.

When I went to check the work, I kept getting an error message. Essentially I wrote this code…

// Add your logging function here:
function logRequest(verb) {
console.log(’${verb} Request Received’);
};

The solution code is this…

// Add your logging function here:
const logRequest = verb => {
console.log(’${verb} Request Received’);
}

Am I doing something wrong? For some reason the little tilde’s don’t show up in my code, so replaced them here with regular single quote characters.

-John


#2
function logRequest(verb) {
    console.log(verb + ' Request Received');
}

The above is the ES5 form that needs to be refactored to ES6+.

is the refactored form of the earlier function.

Both are the same, semantically. Only their syntax is different, with the introduction of const keyword, => (arrow function notation), template literals for string interpolation, and implicit returns.

ES6 syntax permits an unbracketed single parameter. No parameter, or multiple parameters must still be bracketed. Single line code can also be written without enclosing braces, and can drop the return keyword if present. This is known as implicit return and only applies to single line code.

const logRequest = verb => console.log(`${verb} Request Received`);

logRequest(`print`);
Native Browser JavaScript
 > 
 print Request Received
=> undefined
 >

There are some things that we cannot do with arrow functions, but we won’t get into that, just now. It is worth reading up on, though.


#4

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