I have a tsx file with react-native. My function name is underlined if function is not set to const or let with this message:
Cannot find name 'goBack'
goBack = () => {
// do stuff
}
But it works if I set const or let:
const goBack = () => {
// do stuff
}
Why ?
test = (x,y) => {} vs const test = (x,y) => {} In SoloLearn js course, arrow functions are always used with const but they also work without it.
Arrow functions are always unnamed. If the arrow function needs to call itself, use a named function expression instead. You can also assign the arrow function to a variable so it has a name.
Summary. As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable.
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
This doesn't have anything to do with arrow functions. You're trying to assign a value to an identifier you haven't declared anywhere.
This:
goBack = () => {
// do stuff
}
assigns an arrow function to the already declared identifier goBack
. (Or, if this were within a class
, it would create a new property and assigns the arrow function to it — but we know you're not doing this in a class, beacuse your const
version would fail if you were.)
It's exactly like:
answer = 42;
If answer
isn't declared, you get an error from TypeScript.
This:
const goBack = () => {
// do stuff
}
creates a local variable (well, constant) and assigns the arrow function to it, just like:
const answer = 42;
It's useful to remember that arrow functions have no declaration syntax. An arrow function is always an expression. The part to the left of the =
in your examples isn't part of that arrow function expression (although, somewhat surprisingly, it can have an effect on the function that's created).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With