switch và variable scope
Trong JavaScript, mỗi switch tạo ra một variable scope riêng.
tsswitch (true // Variable scope 1) {default:switch (true // Variable scope 2) {default:// ...}}
tsswitch (true // Variable scope 1) {default:switch (true // Variable scope 2) {default:// ...}}
case không có variable scope riêng
Mỗi case không tạo ra variable scope riêng. Khi có nhiều case, toàn bộ switch chia sẻ chung một variable scope. Do đó, khi khai báo cùng tên biến ở nhiều case sẽ xảy ra lỗi runtime.
tsletx = 1;switch (x ) {case 1:constsameName = "A";break;case 2:constsameName = "B";break;}
tsletx = 1;switch (x ) {case 1:constsameName = "A";break;case 2:constsameName = "B";break;}
Trong TypeScript, khi khai báo cùng tên biến sẽ xuất hiện lỗi compile.
tsletx = 1;switch (x ) {case 1:constCannot redeclare block-scoped variable 'sameName'.2451Cannot redeclare block-scoped variable 'sameName'.= "A"; sameName break;case 2:constCannot redeclare block-scoped variable 'sameName'.2451Cannot redeclare block-scoped variable 'sameName'.= "B"; sameName break;}
tsletx = 1;switch (x ) {case 1:constCannot redeclare block-scoped variable 'sameName'.2451Cannot redeclare block-scoped variable 'sameName'.= "A"; sameName break;case 2:constCannot redeclare block-scoped variable 'sameName'.2451Cannot redeclare block-scoped variable 'sameName'.= "B"; sameName break;}
Cách tạo variable scope cho case
Để tạo variable scope cho case, bọc case bằng dấu ngoặc nhọn.
tsletx = 1;switch (x ) {case 1: {constsameName = "A";break;}case 2: {constsameName = "B";break;}}
tsletx = 1;switch (x ) {case 1: {constsameName = "A";break;}case 2: {constsameName = "B";break;}}
Khi làm như vậy, cả lỗi runtime của JavaScript và lỗi compile của TypeScript đều không xảy ra.
Chia sẻ kiến thức
🌏switch trong JavaScript có chung một variable scope cho toàn bộ
😕Không có scope riêng ở mức case
Nếu khai báo cùng tên biến ở nhiều case...
🔥JavaScript → Lỗi runtime
⛔️TypeScript → Lỗi compile
✅Viết {} ở case sẽ tạo scope riêng
Từ 『Survival TypeScript』