Case blocks

Usually, the code following a case or default clause will not only occupy a single line. As such, it has become conventional to wrap these statements with a block, so that there is a sense of containment:

switch (speed) {
case 'slow': {
console.log('Initiating slow speed');
car.changeSpeedTo(speed);
car.enableUrbanCollisionControl();
}
case 'fast': {
console.log('Initiating fast speed');
car.changeSpeedTo(speed);
car.enableSpeedLimitWarnings();
car.enableCruiseControlOption();
}
case 'regular':
default: {
console.log('Initiating regular speed');
car.changeSpeedTo(speed);
}
}

This isn't strictly necessary and doesn't change any functionality, but it does offer more clarity to the reader of our code. It also paves the way for any block-level variables, should we wish to introduce these later. As we know, within a block (delimited with { and }), we can use const and let to declare variables that will be scoped only to that block:

switch (month) {
case 'December':
case 'January':
case 'February': {
const message = 'In the UK, Spring is coming soon!';
// ...
}
//...
}

Here, we're able to declare specific variables that are scoped to the February case only. This is useful if we have a large amount of logic that we'd like to isolate. At this point, however, we should consider abstracting that logic in some other way. Lengthy switch statements can be incredibly hard to understand.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.13.164