Function declaration in ES6?

I wanted to "upgrade" my javascript code to the new ES6 standard, so I looked at how the functions are now executed and tested on my global function, which reads like this in the "old" es5

function logMessage(message) { document.getElementById("logs").innerHTML = document.getElementById("logs").innerHTML + `<li class="item-padding"> ${message} </li>` } 

now, if I am not mistaken, the correct "conversion" to es6 would be as follows:

 logMessage = message => { etc } 

But my ESLint tells me that my logMessage is not defined, and I get an error in my console, will I miss something? Should I declare var, let or const before logMessage?

I don’t know if this is important, but I also want to export this function from the One file to the Two file and use the logMessage function in another function in the Two file, is there something I should remember about this

Thanks for any help!

Edit: Thanks to everyone that the answers helped me a lot, the problem has been fixed!

+8
javascript function ecmascript-6 arrow-functions
source share
2 answers

now, if I'm not mistaken, the correct "conversion" to es6 will be like this:

You are wrong.

Arrow Functions - New syntax with different behavior. This is not a direct replacement for function declarations and function expressions (both of which still exist in ES6).

But my ESLint tells me that my logMessage is not defined, and I get an error in my console, will I miss something? Should I declare var, let or const before logMessage?

Yes. You assign something to a variable. You must first declare a variable .

I also want to export this function from One file to Two file

As you determine, a function does not affect your ability to export it.

+13
source share
 function logMessage(message) { // etc... } 

... is a function declaration that still works great in es6. You convert a function declaration into a function expression that in es5 will look like this ...

 logMessage = function(message) { // etc... } 

... and then in es6 ...

 logMessage = message => { // etc } 

... therefore, the problem with the line is not introduced by es6 syntax, but rather it uses a function expression, assigning it to a variable, which without the var / let / const variable is a global variable. There is also a difference in the initial declaration of the function, but the form of the function expression must be declared before it is called. There is also a difference in that the es6 arrow functions preserve the context of this from the parent area, so it is worth noting that they are not 100% direct 1 for 1 comparisons of each other.

The short answer is yes, the variables must be declared with var / let / const , so as not to become global variables, regardless of whether it is a function or not.

 let logMessage = message => { // etc } 
+10
source share

All Articles