LoginSignup
1
1

More than 1 year has passed since last update.

JavaScriptで長くなりがちな条件式を簡潔にまとめるって話

Last updated at Posted at 2022-08-15

コードを書いていると、if文の条件式が長くなることはありませんか?

よくあるのが、ユーザ権限まわりの分岐ですかね~
この権限とこの権限はこっちの処理するみたいなやつ!

そんな時は、Array.includes()を使うとスッキリ読みやすいコードを書くことが出来ます!!

まずは読みづらいコード😣

if (authority === 'DOG' || authority === 'CAT' || authority === 'MONKEY' || authority === 'RABBIT') {
  // 🐶🐱🐵🐰の処理
} else {
  // その他の処理
}

Array.includes() を使って読みやすくする🤗

const authList = ['DOG', 'CAT', 'MONKEY', 'RABBIT']
if (authList.includes(authority)) {
  // 🐶🐱🐵🐰の処理
} else {
  // その他の処理
}

変数に判定結果をスッキリ格納できる

const isAuthed = [
  'DOG',
  'CAT',
  'MONKEY',
  'RABBIT',
].includes(authority)

もちろんswitchでもOK!

状況によっては、switch - caseで書くことも出来ます!

switch(authority) {
  case 'DOG': 
  case 'CAT': 
  case 'MONKEY':
  case 'RABBIT':
    // 🐶🐱🐵🐰の処理
    break
  default:
    // その他の処理
}

分岐後の処理が長くなると読みづらくなることがあるので注意が必要です📌

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1