DEV Community

Discussion on: Is there a good temporary variable name that you use?

Collapse
 
blindfish3 profile image
Ben Calder

My first suggestion would be to declare variable names that match the response object:

const items = response.items;

Then assuming your API has a sensible naming convention - i.e. a plural for groups of elements - you can use the singular in your iteration. But you should consider looping with an Array method instead; because then you can get rid of a lot of the temporary variables:

response.items.forEach(item => {
  // do stuff with each item
});
Enter fullscreen mode Exit fullscreen mode

I should add that typically your API call will be async so you would expect to either use a Promise or an await there ;)
You would also usually add a guard to make sure you have a response to work with.

Collapse
 
klvenky profile image
Venkatesh KL • Edited

Thanks Ben. I do understand that using array methods would make reduce the no. of temporary variables. I've kept it simple enough so that people coming from any language would understand. That's the reason I have removed await as well.
Also if it's in JavaScript, we may have to use something like bluebird to ensure all api calls are complete.

Also there are some instances where I'd like to have multiple tokens as in previous example. I will have a token for foo call, another for each of the api call for bar.
It can essentially become something like:
1 foos -> 1 bar requests(at least) -> 1 bar request can have multiple pages to query for.