5 ms·
For some use cases, the difference can be a little more dramatic. fetch(allResourcesUrl).then(async response => { let allResources = await response.j
by TimTheTinker 7y ago
For some use cases, the difference can be a little more dramatic.
fetch(allResourcesUrl).then(async response => {
let allResources = await response.json();
let pageResource = await (await fetch(allResources.page1.url)).json();
// set up page with pageResource
});
can be replaced with
{
let allResources = await (await fetch(allResourcesUrl)).json());
let pageResource = await (await fetch(allResources.page1.url)).json();
//set up page with pageResource
}
Note use of a top-level block instead of a function context to hide local variables.
- elyobo 7y agoWhat's with the `let` though?
- joshAg 7y agolet plus the curly bracket scoping means that the variables only exist within the curly brackets, and not the global state.
- aledalgrande 7y agoMaybe he meant why not const?
- spartanatreyu 7y agoYou would use const, unless you wanted to reassign the variable later in the same scope.
- earthboundkid 7y agoConst is a complete waste of time for non-primitive types. I defy anyone to show me a single bug in a popular program that could have been prevented by using const for a function local object. It can’t be done. There are bugs caused by mutatable state. There are bugs caused by reassigning globals. There has never been a bug caused by reassigning a function local variable while leaving it mutable.
- aledalgrande 7y agoBy waste of time do you mean performance or coding time? I feel like writing a character more is not a waste of time, if you are just following the convention that anything that is not going to be muted should be signed explicitly. It's not to prevent bugs, but for readability and ease of use.
- earthboundkid 7y agoTime deciding if you can/should rebind a variable or not is a waste of developer time.
- elyobo 7y agoI sort of agree; I solve this by never using let and never rebinding :) No need to think about it at all.
- earthboundkid 7y agoThen you end up playing this game of jumping through hoops to omit variables. It's a tempting waste of time because it feels productive.
- elyobo 7y agoStrangely it turns out that rebinding variables is a really uncommon need, so there's pretty much zero game playing.
- aledalgrande 7y agoThen when you will have to change or debug the same code instead of writing new, you will have to spend more time understanding what variable is the source of a state change, for example inside a loop. That is more of a waste of time to me.
- jhomedall 7y agoYou will know ahead of time whether you're going to be rebinding a variable. The use of const is a hint to the next person reading your code, since they won't be privy to your thought process. In an ideal world, const would be the default, and you would have to opt into non-const.
- elyobo 7y agoCorrect. Example doesn't show modification of the variables later, better to use const.