Control structures: switch - 12

- Andrés Cruz

En español
Control structures: switch - 12

Without a doubt, the conditional structure, that is, the if, is the most used control structure today; but as you can see, when you have multiple conditions, a conditional becomes impractical; due to the poor readability of the code for these cases, there is a structure called switch which allows grouping a set of expressions in a more simplified way:

switch(day) {
  case 1: weekday = "Monday."; break;
  case 2: weekday = "Tuesday."; break;
  case 3: weekday = "Wednesday."; break;
  case 4: weekday = "Thursday."; break;
  case 5: weekday = "Friday."; break;
  case 6: weekday = "Saturday."; break;
  case 7: weekday = "Sunday."; break;
}

As you can see, instead of evaluating repeated conditions for the same entity, we simply place the value, which can be anything and as complex as you want; In this case we are simply evaluating what day it is from a numerical representation of the day of the week; but maybe you are interested in evaluating texts, booleans, or complex conditions like the one we covered in previous videos.

The use of break may sound a bit familiar to you; which, as its name indicates, is a reserved word that we can use to break with the rest of the execution of the block or in this more specific case with the control structure; Therefore, when a match is found for the value we are comparing, the execution of the rest of the switch block will simply stop.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.