Greg Gum
Greg Gum

Reputation: 38129

What does this example code do?

I found this example on jetbrains.com

async function getWeather(cityid: number){
    var weather = await getForecast(cityid);
    var {t: temperature, h: humidity} = weather;
    return { temperature, humidity};
}

I understand async/await, but I am trying to understand what is going on with the last two lines.

var {t: temperature, h: humidity} = weather;

As far as I can tell, this is creating a var with two properties, t of type temperature, and h of type humidity.

return { temperature, humidity};

To me, this looks like it is returning a new object with two child objects, temperature and humidity. I don't get how it is getting that from the weather object.

I don't know if this is a javascript question, or a typescript question, so I am tagging as both.

Upvotes: 4

Views: 95

Answers (2)

Griffith
Griffith

Reputation: 3217

var {t: temperature, h: humidity} = weather; is a very powerful new syntactic feature from ES6 called destructing.

Assume that weather is an object { t: 60, h: 20 }. Traditionally, when we want to assign the properties of weather into local variables, we would do something like:

var temperature = weather.temperature;
var humidity = weather.humidity; 

This is really inconvenient and will be increasingly tiresome as the object grows more complex. With destructing, we can now use

var {t: temperature, h: humidity} = weather;
console.log(temperature); // 60
console.log(humidity); // 20

And have the local variables temperature and humidity already defined and ready for use.

Deconstructing also provides a shorter syntax for cases when the "target" variables are the same as the "source" variables. In the case of weather, instead of writing:

var {t: t, h: h} = weather;
console.log(t); // 60
console.log(h); // 60

We can just write:

var {t, h} = weather;
console.log(t); // 60
console.log(h); // 60

Upvotes: 4

basarat
basarat

Reputation: 276313

var {t: temperature, h: humidity} = weather;

This is called destructuring. It is a concept covered here : https://basarat.gitbooks.io/typescript/content/docs/destructuring.html

Here you are saying put weather.t into temprature and weather.h into humidity

return { temperature, humidity};

This is returning an object with properties temprature and humidity. This is shorthand for : return { temperature:temperature, humidity:humidity};. This is one of the new notations in ES6 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer

Upvotes: 5

Related Questions