Grateful
Grateful

Reputation: 10175

Within React, why am I not able to use nested arrow functions... Altough normal functions seem to work?

The following doesn't work.

generateFakeAnswer = () => {
    getRealAnswer = (state) => {
      return state.valueOne + state.valueTwo + state.valueThree;
    }

    this.setState({
      fakeAnswer: Math.floor(Math.random() * 10) + getRealAnswer(this.state)
    })
  }

But the following does work.

generateFakeAnswer = () => {
    function getRealAnswer(state) {
      return state.valueOne + state.valueTwo + state.valueThree;
    }

    this.setState({
      fakeAnswer: Math.floor(Math.random() * 10) + getRealAnswer(this.state)
    })
  }

Am I doing something wrong?

Upvotes: 2

Views: 176

Answers (1)

b3hr4d
b3hr4d

Reputation: 4538

If you already don't have let getRealAnswer You should make a new const inside your function.

Strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern JavaScript). Assignments, which would accidentally create global variables, instead throw an error in strict mode:

                       // Assuming no global variable mistypeVariable exists
mistypeVariable = 17;  // this line throws a ReferenceError due to the
                       // misspelling of variable

So you function should be like this:

generateFakeAnswer = () => {
    const getRealAnswer = (state) => {
      return state.valueOne + state.valueTwo + state.valueThree;
    }

    this.setState({
      fakeAnswer: Math.floor(Math.random() * 10) + getRealAnswer(this.state)
    })
}

Upvotes: 3

Related Questions