switch / case statement
Ko'p variantli qaror qabul qilish uchun switch/case. Qachon if/else, qachon switch ishlatiladi.
switch / case — aniq tanlov
Bir qiymatni ko'p holat bilan solishtirish uchun eng o'qilishi oson vosita.
Dars rejasi
5 ta mavzu1. switch sintaksisi
switch bir qiymatni (qavs ichida) bir nechta holat (case) bilan === orqali solishtiradi. Qaysi case mos kelsa — uning bloki ishlaydi.
1const rang = "qizil";2
3switch (rang) {4 case "qizil":5 console.log("To'xta!");6 break;7 case "sariq":8 console.log("Ehtiyot bo'l");9 break;10 case "yashil":11 console.log("Yura ber");12 break;13 default:14 console.log("Noma'lum rang");15}2. break va default
break
case topilgandan so'ng switch'dan chiqish. Bo'lmasa — keyingi case'larga «oqib» o'tadi.
default
Hech qaysi case mos kelmasa ishlaydi. if/else'dagi else bilan bir xil.
1const ball = 5;2
3switch (ball) {4 case 5:5 console.log("A'lo");6 // break yo'q!7 case 4:8 console.log("Yaxshi");9 // break yo'q!10 case 3:11 console.log("Qoniqarli");12 break;13}14// Natija: A'lo, Yaxshi, Qoniqarli (hammasi!)3. Bir necha case — guruhlash
Bir xil natijani bir nechta case uchun olish kerak bo'lsa — ularni ketma-ket yozamiz (break'siz).
1const kun = "shanba";2
3switch (kun) {4 case "dushanba":5 case "seshanba":6 case "chorshanba":7 case "payshanba":8 case "juma":9 console.log("Ish kuni");10 break;11 case "shanba":12 case "yakshanba":13 console.log("Dam olish kuni!");14 break;15 default:16 console.log("Bunday kun yo'q");17}4. switch vs if/else
switch qachon?
Bitta o'zgaruvchini ko'p aniq qiymatlar bilan solishtirish kerak bo'lsa.
if/else qachon?
Oraliq, >=, <= yoki murakkab mantiq kerak bo'lsa. Masalan: ball >= 90.
1// if/else bilan2const rol = "admin";3if (rol === "admin") {4 console.log("To'liq ruxsat");5} else if (rol === "moderator") {6 console.log("Qisman ruxsat");7} else {8 console.log("Oddiy foydalanuvchi");9}10
11// switch bilan (ancha toza)12switch (rol) {13 case "admin":14 console.log("To'liq ruxsat");15 break;16 case "moderator":17 console.log("Qisman ruxsat");18 break;19 default:20 console.log("Oddiy foydalanuvchi");21}5. Amaliy misollar
1function oyNomi(n) {2 switch (n) {3 case 1: return "Yanvar";4 case 2: return "Fevral";5 case 3: return "Mart";6 case 4: return "Aprel";7 case 5: return "May";8 case 6: return "Iyun";9 case 7: return "Iyul";10 case 8: return "Avgust";11 case 9: return "Sentyabr";12 case 10: return "Oktyabr";13 case 11: return "Noyabr";14 case 12: return "Dekabr";15 default: return "Xato";16 }17}18
19console.log(oyNomi(4)); // "Aprel"20console.log(oyNomi(13)); // "Xato"Kichik test
0 / 41.switch qaysi operator bilan solishtiradi?
2.Agar break yozmasangiz nima bo'ladi?
3.default qachon ishlaydi?
4.Qachon switch o'rniga if/else yaxshiroq?