Skip to content

Instantly share code, notes, and snippets.

@o0101
Created April 18, 2018 10:03
Show Gist options
  • Save o0101/7f5e4e492487a9f6cf497f0293be17b8 to your computer and use it in GitHub Desktop.
Save o0101/7f5e4e492487a9f6cf497f0293be17b8 to your computer and use it in GitHub Desktop.
Switch Branch + Block Scope : ECMAScript

Block scope can be used in switch statements. It's sort of a nice syntax that allows you to defined same-named variables without getting 'already defined' errors.

The example is not so great because data could be rewritten to be let data; at the top of the function, rather than in each case block.

Blocking scoping is pretty useful.

async function branchOnAction( event ) {
let response;
switch( event.action ) {
case 'create': {
const data = Object.assign( {method:'POST'}, event.data );
response = await req(data);
break;
} case 'read': {
const data = Object.assign( {method:'GET'}, event.data );
response = await req(data);
break;
} case 'update': {
const data = Object.assign( {method:'PATCH'}, event.data );
response = await req(data);
break;
} case 'delete': {
const data = Object.assign( {method:'DELETE'}, event.data );
response = await req(data);
break;
}
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment