Why arrow function name must be const/let?
Asked Answered
P

1

7

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 ?

Personage answered 23/7, 2019 at 10:13 Comment(3)
That depends on where it is defined in your "tsx file". Is it inside a class (thus being a property of that class), or is it outside of a class definition? The former is allowed, while the latter isntGemot
Somehow it seems unlikely that your question is related to tsx...Weigand
Sure, makes sense. Do you have an ambient variable named goBack defined somewhere? That is what you are trying to assign a value to. If not you need a local one and you do that with either let/var/const. This is not just an arrow function, it would also have this error if you did a simple string assignment.Cicely
W
10

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).

Weigand answered 23/7, 2019 at 10:19 Comment(2)
Ah ok! Thanks! So what's better ? function goBack() or const goBack = () => {}Personage
@Personage - Either, depending on various things. Do you need it to close over this? Use an arrow function. Do you need it to be fully hoisted? Use a traditional function declaration. Do you want to find it by searching for function goBack in your code? Use a traditional function. Are you going to use new with it? Use class or a function. If you don't care about this or hoisting and you're not going to use new with it, it's a matter of style whether you use an arrow function or a traditional function.Weigand

© 2022 - 2024 — McMap. All rights reserved.