What does the at symbol (@) do in ES6 javascript? (ECMAScript 2015)

Kevin Wu picture Kevin Wu · Aug 5, 2015 · Viewed 21.9k times · Source

I'm looking at some ES6 code and I don't understand what the @ symbol does when it is placed in front of a variable. The closest thing I could find has something to do with private fields?

Code I was looking at from the redux library:

import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'redux/react';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/CounterActions';

@connect(state => ({
  counter: state.counter
}))
export default class CounterApp extends Component {
  render() {
    const { counter, dispatch } = this.props;
    return (
      <Counter counter={counter}
               {...bindActionCreators(CounterActions, dispatch)} />
    );
  }
}

Here is a blog post I found on the topic: https://github.com/zenparsing/es-private-fields

In this blog post all the examples are in the context of a class - what does it mean when the symbol is used within a module?

Answer

Kryten picture Kryten · May 24, 2016

I found the accepted answer was not enough to help me sort this out, so I'm adding a little more detail to help others who find this.

The problem is that it's unclear exactly what is the decorator. The decorator in the example given is not just the @ symbol, it's the @connect function. Simply put, the @connect function is decorating the CounterApp class.

And what is it doing in this case? It's connecting the state.counter value to the props of the class. Remember that in redux the connect function takes two arguments: mapStateToProps and mapDispatchToProps. In this example, it's taking only one argument - mapStateToProps.

I haven't investigated this too much, but this appears to be a way to encapsulate your state-to-props and dispatch-to-props mappings so they accompany your components rather than being located in a different file.