Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Galago's avatar

How to define class variables in ES6

Hello,

I want to use Ecmascript 6 and in order to learn its features and syntax, I watched this video. In this video, Jeffrey is using the following way to define class variables:

class Counter {
    
    count = 0;

    //Rest of code

but when I try to do this as well, I get the following error in my console (when executing the gulp command):

{ SyntaxError: C:/xampp/htdocs/exchange/resources/assets/js/Counter.js: Unexpected token (3:7)
  1 | class Counter {
  2 |
> 3 |   count = 0;
    |         ^
  4 |
  5 |   constructor() {
  6 |

from which I assume this way of defining class variables is deprecated. Or am I doing something wrong? And if I don't, what is the best practice to define class variables?

Thanks in advance.

0 likes
4 replies
ejdelmonico's avatar

Yea, that is not correct and will throw an error in eslint. Use const for most variables in ES6. If you are defining a variable that is going to change its value, then use let. There is no requirement to declare variable at the top in ES^ either. In the case above, counter is expected to change its value so I would use let. Also, I believe let is the default when not declaring but its not common to use it that way.

Galago's avatar

@ejdelmonico, like so?

class Counter {

    let count = 0;
}

because that gives the same error.

jimmck's avatar

class Counter { constructor() { this.count = 0; ... } }

Galago's avatar

@jimmck, is that the only way to define them? Because I knew about defining them in your constructor and I actually don't like that.

Please or to participate in this conversation.