1

I'm working through some CodeWars katas and I would like to know: For what reason does this syntax work...

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return Math.min(...args)
  }
}

...but this other does not?

class SmallestIntegerFinder {
  const findSmallestInt = args => Math.min(...args)
}

This is the error trace printed:

const findSmallestInt = args => Math.min(...args)
      ^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at 
    at evalScript (bootstrap_node.js:353:27)
    at run (bootstrap_node.js:122:11)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:121:9)
    at bootstrap_node.js:504:3

I haven't had any problem using the second syntax in other katas, but this is the first time I use it inside a class, so I guess it has something to do with JavaScript classes that I haven't learnt yet or something else that is escaping me at the moment.

Thanks in advance!

3
  • 2
    ES6 does not support fields in class literals. Commented Feb 20, 2018 at 1:05
  • Because a class body is not a block that could hold arbitrary statements? Commented Feb 20, 2018 at 1:15
  • Would you have expected const … = … to work inside an object literal? Commented Feb 20, 2018 at 1:16

1 Answer 1

4

It's because that's not valid syntax. Within a class, you do not use variable bindings like const, let, or var to define members. The syntax is nice and simple.

There is a proposal, however, that will allow class fields, similar to your second example. However, you would still not use const, let, or var to define these either.

Edited: thanks @Bergi for pointing out that class/instance method syntax isn't sugar for anything, that's just how you define methods.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually, the method definition syntax is not a shorthand for anything, it's the only valid syntax inside a class body. Notice that in contrast to object literals, there are no commata either.
Thank you all! I guess my error was considering that functions and class methods could use the same syntax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.