Why can't I define a method inside a class with the keyword function?

So, I don’t even know if the tittle statement is correct. But I get an error while doing so. So, which is the syntax rule in js, that does not let me do that? I can’t find on MDN the reason.

Well, you can, sort of. These (afaik) are the three ways to declare a class method:

class MyClass {
  myMethod1() {
    console.log('my method 1');
  }
  myMethod2 = function() {
    console.log('my method 2');
  };
  myMethod3 = () => {
    console.log('my method 3');
  };
}

const val = new MyClass();

val.myMethod1();
// my method 1
val.myMethod2();
// my method 2
val.myMethod3();
// my method 3

So, the first is the “normal” way to declare a class method. The other two are creating a class property and storing an anonymous function in it.

But I guess that you are asking why you can’t do:

class MyClass {
  function myMethod1() {
    console.log('my method 1');
  }

I imagine because it wasn’t designed that way. The gods of JS had to make a decision about how a class method is declared. In a normal JS function, you had to have the keyword to make it clear that you were declaring a variable. But in a method, the structure makes it clear that it is a method declaration (it can’t be being called) so they decided that it isn’t necessary. They could have required it, but they chose not to. There was no need to allow both.

I’m kind of guessing there, but it makes sense.

1 Like

It’s a description of an object, objects can’t do that:

{
  property1: "some property",
  function property2 () {
    // syntax error
  },
}

Same way you can’t do this:

var function example () {
  // syntax error
}

function is a keyword, it denotes a specific thing that the JS interpreter should do at that point. The semantics and syntax of variable declarations and object properties also denote specific things. If the two are can be confused, it may make it harder to write compilers/interpreters for the language as would need to include more logic to differentiate between things. It’s just a design trade-off. It’s not necessarily a good trade-off, but it’s just how the language works. To see exactly why the language semantics are that way, you’d need to look at the spec (which describes how each part of the language should work).

1 Like