Hi all,
I normally refer to variables as currValue, currentValue etc. I find it very intuitive myself. However, recently after seeing lot of people who don't find it clear, I would like to know if there's a better way to do so.
Following is the code where I use a temporary variable which I think can be named well.
function apiCall(type string, options Object(optional)) {
// ... some code
// response format
// { nextPageToken <string>, items: <Array of Objects> }
}
function getAllFooBar() {
// find smart_collections
const response = apiCall('foo');
const fooValueNextToken = response.nextPageToken;
const fooValues = response.items;
const barValues = [];
// for every foo value
for(let i=0; i< fooValues.length; i++) {
const currFooValue= fooValues[i];
let hasToken = true // setting true initially
let token = null
while(hasToken) {
if (token!= null) {
fooValue.token = token;
}
const innerResponse = apiCall('bar', currFooValue)
// Is there a better way to name these variables?
const currToken = innerResponse.nextPageToken;
const currValues = innerResponse.items;
barValues.push(...currValues); // saving the values received from api into allValues
hasToken = currToken != null
token = currToken
}
}
}
If you see the above code, I am getting some values from api and then iterating over to fetch another set of values.
I know this is not a question that's so important. But, I am someone who think that people modify code more often than they assume. So, I would like to know if there's a good way to make sure everyone is on the same page?
thanks in advance
cheers
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:
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.