Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Object with variable as a key and value

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

like image 669
Mario Avatar asked Jan 17 '18 20:01

Mario


1 Answers

{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.

like image 146
Shubham Khatri Avatar answered Sep 19 '22 06:09

Shubham Khatri