Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 381
Greg Gum Avatar asked Jan 08 '23 07:01

Greg Gum


1 Answers

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

like image 60
basarat Avatar answered Jan 21 '23 21:01

basarat