Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why arrow function name must be const/let?

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 ?

like image 450
Cracky Avatar asked Jul 23 '19 10:07

Cracky


People also ask

Do arrow functions need const?

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.

Can arrow functions be named?

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.

Why would you use const over Let?

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.

What does () => mean in JavaScript?

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.


1 Answers

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

like image 107
T.J. Crowder Avatar answered Nov 15 '22 04:11

T.J. Crowder