6

Whats the difference between functions declared with const and functions declared without let or const and a function declared otherwise in an ES6 class?

class App extends Component {

    submitFood = () =>{
        // some code
    }

Why does the above work OK but the declaration below give an error:

class App extends Component {

    const submitFood = () =>{
        // some code
        }
jojojohn
  • 725
  • 2
  • 10
  • 19
  • 2
    Because they are `member functions` or `methods` and are part of the `Class` you declare. – Nandu Kalidindi Oct 26 '17 at 15:50
  • 1
    It's not always clear how to answer questions that ask "why is this not valid syntax". It's not valid syntax because the language simply doesn't allow it. Or do you want to know the reason behind the decision to not allow this syntax? In that case you have to talk to the people who made that decision. – Felix Kling Oct 26 '17 at 17:01
  • They're both invalid ES6, so I'd say it's not much difference. – Bergi Oct 26 '17 at 17:32

2 Answers2

5

First of all: None of the examples you provided is valid ES6. The grammar rules for ES6 classes only allow methods definitions inside the class body. I.e.

class MyClass {
  method1() {}
  method2() {}
}

The first example however is making use of the class fields proposal. This proposal extends the existing grammar to allow the definition of properties of the form

class MyClass {
  someProperty = value;
}

These assignments are not evaluated at class definition time but at instantiation time. It's syntactic sugar for assigning properties in the constructor:

class MyClass {
  constructor() {
    this.someProperty = value;
  }
}

Your second example is simply invalid syntax because there are no grammar rules that allow putting let or const before the class field.

Keep in mind that class fields are not variable declarations or variable assignments.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
-3

const submitFood = () =>{ // some code }

Is the creation of function (submitFood=() {}) and the creation of a variable so usual rules in variable hosting blocked let and const.
so fail since submitFood() is not defined. (It will throw a ReferenceError).

Gamsh
  • 545
  • 4
  • 21