The class introduced in ES6 allows class members or properties to be initialized in the constructors only.

For example, id and name are members of the Employee class,

  • ID initialized in the constructor
  • the name is initialized outside the constructor, which gives a compilation error in ES6

Here is an example

class Employee {
  constructor() {
   this.id=1;
  }
  //name="John"; invalid in ES6
}

var emp=new Employee()
console.log(emp.id)

ES7 Class member variables

With the ES7 release, You can initialize the members without writing in the constructor.

class Employee {
  constructor() {
   this.id=1;
  }
  name="John";
}

var emp=new Employee()
console.log(emp.id)

We can use the same syntax in React components

Without ES7, the React component is declared as given below The state is initialized in Constructor only.

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

The same component can be rewritten using ES7 class properties the state is a property of to React component, so declared outside the constructor.

class Clock extends React.Component {
 state = {date: new Date()};
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}