DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Ryo Kuroyanagi
Ryo Kuroyanagi

Posted on

Avoiding `let` in TypeScript

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
}
Enter fullscreen mode Exit fullscreen mode

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"
  }
})()
Enter fullscreen mode Exit fullscreen mode

Hope this makes your code more cleaner!

Top comments (5)

Collapse
 
hamodey85 profile image
Mohammed Almajid • Edited on

or we can do

const fruitNum = 0;
const fruitName = {
  0: 'Apple',
  1: 'Banana',
  default: 'Unknown',
};

fruitName[fruitNum] ?? fruitName.default;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ku6ryo profile image
Ryo Kuroyanagi

good to know !

Collapse
 
kychok98 profile image
Chok Kah Yang

Will it affect the performance?

Collapse
 
ku6ryo profile image
Ryo Kuroyanagi • Edited on

I got an interesting result.

I ran the same test for 4 rounds for 3 methods for 50,000,000 times each.

  1. Using let
  2. Using anonymous function (This is my method in this article)
  3. Using dictionary (Object - Mohammed's idea)

At the first round, let is much faster than others. But at round 2, 3 and 4, the runtime of let 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.

Round 1
Using let: 55.4 ms
Using anonymous fun: 317.1 ms
Using dictionary: 516.4 ms

Round 2
Using anonymous fun: 320.3 ms
Using dictionary: 520.3 ms
Using let: 312.7 ms

Round 3
Using dictionary: 516.1 ms
Using let: 315.3 ms
Using anonymous fun: 328.3 ms

Round 4
Using let: 317.9 ms
Using anonymous fun: 329.7 ms
Using dictionary: 522.3 ms
Enter fullscreen mode Exit fullscreen mode

let and anonymous fun does not have much difference but dictionary is a bit slower than others. I guess the cause is that the speed of accessing a dictionary is slower than value comparison (--> switch).

Collapse
 
hamodey85 profile image
Mohammed Almajid

I thought dictionary faster than others

Stop sifting through your feed.

Find the content you want to see.

Change your feed algorithm by adjusting your experience level and give weights to the tags you follow.