Babel: switch...case duplicate declaration warning

Created on 24 Jun 2015  路  2Comments  路  Source: babel/babel

function switchCaseWarn(arg) {
  switch(arg) {
    case 'A':
      let name = 'Apple';
      break;
    case 'J':
      let name = 'Jackfruit';
      break;
  }
}

Line 7: Duplicate declaration "name"

At any given time only one case statement will be executed and therefore name is not likely to be duplicated.

Is the warning accurate? I imagine every case block has its own scope and variable declared inside it cannot leak to outer scope. Or am I missing something?

outdated

Most helpful comment

switch statements introduce a new block scope around the whole switch body (the curly brackets). There no block scope introduced by individual case statements. Imagine for instance:

function switchCaseWarn(arg) {
  switch(arg) {
    case 'A':
      let name = 'Apple';
    case 'J':
      let name = 'Jackfruit';
      break;
  }
}

would be invalid because let name is declared twice.

You can however add new block scopes by adding your own {}s manually if you want, just like you can anywhere else:

function switchCaseWarn(arg) {
  switch(arg) {
    case 'A': {
      let name = 'Apple';
      break;
    }
    case 'J': {
      let name = 'Jackfruit';
      break;
    }
  }
}

All 2 comments

switch statements introduce a new block scope around the whole switch body (the curly brackets). There no block scope introduced by individual case statements. Imagine for instance:

function switchCaseWarn(arg) {
  switch(arg) {
    case 'A':
      let name = 'Apple';
    case 'J':
      let name = 'Jackfruit';
      break;
  }
}

would be invalid because let name is declared twice.

You can however add new block scopes by adding your own {}s manually if you want, just like you can anywhere else:

function switchCaseWarn(arg) {
  switch(arg) {
    case 'A': {
      let name = 'Apple';
      break;
    }
    case 'J': {
      let name = 'Jackfruit';
      break;
    }
  }
}

Ok! Thanks!

Was this page helpful?
0 / 5 - 0 ratings