5

I am learning react and I am following the quick start guide, In the topic Lifting State Up I found the Calculator component

class Calculator extends React.Component {
    constructor(props) {
      super(props);

      ...

      this.state = {scale: 'c', temperature: ''}
    }

    handleCelsiusChange(temperature) {
      this.setState({scale: 'c', temperature})
    }

    handleFahrenheitChange(temperature) {
      this.setState({scale: 'f', temperature});
    }

    render() {
      ...

      return (
        <div>
          ...
        </div>
      )
    }
  }

My question is about this sentence this.setState({scale: 'c', temperature}) here I am expecting this.setState({scale: 'c', temperature: temperature}).

Is this temperature assignation some react sintax sugar? Could you please explain me why this works.

Thanks

1
  • Note this has nothing to do with setState(). This is syntax for the object literal as described in the answers. Commented Jan 17, 2018 at 20:52

2 Answers 2

6

{scale: 'f', temperature} is basically a Property value shorthand syntax for {scale: 'f', temperature: temperature},

So in JavaScript with ES6/ES2015, if you want to define an object who's keys have the same name as the variables passed-in as properties, you can use the shorthand and simply pass the key name.

Check this doc for the details

An important thing to note while using this syntax is, the JS engine looks in the containing scope for a variable with the same name.

If it is found, that variable’s value is assigned to the property.

If it is not found, a ReferenceError is thrown. It’s worth noting that the transpilers will not throw an error at compile time if the variable is not found, but instead will declare an object with the name of the not-found variable.

However, when the code runs you will still get the ReferenceError since the variable does not exist.

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

Comments

2

This is some javascript syntax sugar.

It's a pretty common case to do something along the lines of:

const obj = {
    a: a,
    b: b,
    c: c
};

where you are building an object out of variable you already have and keeping their same names. But you'll notice that you're having to write each variable name twice. So instead, you can write:

const obj = { a, b, c };

and it will be evaluated the same as the above code.

Comments

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.