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 ?

Cracky
  • 97
  • 1
  • 8
  • 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 isnt – nbokmans Jul 23 '19 at 10:15
  • 3
    Somehow it seems unlikely that your question is related to [tag:tsx]... – T.J. Crowder Jul 23 '19 at 10:17
  • 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. – Igor Jul 23 '19 at 10:18

1 Answers1

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Ah ok! Thanks! So what's better ? function goBack() or const goBack = () => {} – Cracky Jul 23 '19 at 10:26
  • 1
    @Cracky - 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. – T.J. Crowder Jul 23 '19 at 10:38