I sometimes feel I am forced to use let
instead of const
in TypeScript even I want to use const
to prevent reassignments.
When we use if
or switch
, there are cases that seems we need to use let
. However, we do not have to use let
actually.
const fruitNum: number = 0 // a number to represent a type of fruit
let fruitName: string = "Unknown"
switch(fruitNum) {
case 0:
fruitName = "Apple"
break
case 1:
fruitName = "Banana"
break
default:
break
}
Instead of the above code, we may want to use a anonymous function to make fruitName
a const
.
const fruitNum: number = 0 // a number to represent a type of fruit
const fruitName: string = (() => {
switch(fruitNum) {
case 0:
return "Apple"
case 1:
return "Banana"
default:
return "Unknown"
}
})()
Hope this makes your code more cleaner!
Top comments (5)
or we can do
good to know !
Will it affect the performance?
I got an interesting result.
I ran the same test for 4 rounds for 3 methods for 50,000,000 times each.
At the first round,
let
is much faster than others. But at round 2, 3 and 4, the runtime oflet
was much different than the round 1. I think the first round may be including certain initial condition (I do not know the details though). Let's see the last 3 rounds.This is my code.
let
andanonymous fun
does not have much difference butdictionary
is a bit slower than others. I guess the cause is that the speed of accessing a dictionary is slower thanvalue comparison (--> switch)
.I thought dictionary faster than others