Creating an object with a variable as a key and value

I study the reaction, and I follow the quick start guide , in the section Lifting 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 about this sentence is this.setState({scale: 'c', temperature}) here I expect this.setState({scale: 'c', temperature: temperature}) .

Is this temperature intended, do some respond to sintax sugar? Could you explain to me why this works.

thanks

+5
source share
2 answers

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

So, in JavaScript with ES6/ES2015 , if you want to define an object whose keys have the same name as the variables passed as properties, you can use the short name and just pass the key name.

Check doc for details

It is important to note that when using this syntax, the JS engine looks in the addition area for a variable with the same name.

If found, this property is assigned the value of a variable.

If it is not found, the value ReferenceError selected. It is worth noting that transpilers will not cause an error during compilation if the variable is not found, but instead declares an object with the name of the variable not found.

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

+6
source

This is javascript syntax sugar.

This is a fairly common case of doing something like:

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

where you build an object from a variable that you already have and keep the same names. But you will notice that you need to write each variable name twice. So instead you can write:

 const obj = { a, b, c }; 

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

+2
source

Source: https://habr.com/ru/post/1274775/


All Articles