[分享] 不允許在case/default中進行宣告 (no-case-declarations)
Published in
2 min readAug 12, 2019
(前略)
switch (prop) {
case 'genre':
let genre = genreFormatter(user[prop])
(後略)
}
本章節switch的練習中, 當我在case底下宣告變數時,
ESLint出現了警告
Unexpected lexical declaration in case block.
稍微查詢了一下,
在case/default中做宣告, 這件事情有蠻多討論。
因為很多人一run程式就報錯, 不明所以。
ESLint雖然出現了警告, 但本章節案例的情況是可以run的。
可是, 如果是像這樣, 在兩個不同的case下宣告了同名的變數, 就會報錯。
const action = 'hello'
switch (action) {
case 'hello':
let msg = 'hello'
console.log(msg)
break;
case 'hi':
let msg = 'hi'
console.log(msg)
break;
}
// SyntaxError: Identifier 'msg' has already been declared
這是因為, let msg的宣告, 會被程式判定為在同一個作用域中重複宣告, 所以報錯。
解決的方法很容易, 只要加上花框{ }, 明確的告訴JS不同case的作用域也不同。
const action = 'hello'
switch (action) {
case 'hello':{
let msg = 'hello'
console.log(msg)
break
}
case 'hi':{
let msg = 'hi'
console.log(msg)
break
}
}
// hello
參考:
no-case-declarations - Rules - ESLint中文
switch - JavaScript | MDN