JavaScript Scratches

Switch

Another flow control statement, similar to a loop, is a tricky one to explain.

It is similar to the 'if / else' conditional situation, in that it deals with several options.

We're going to ask the user for a week day, and depending on which one they enter, perform an action.

What is your favorite day of the week?

 

<script>
function Clear() {
	document.getElementById("FavDay").value="";
	document.getElementById("DayFav").innerHTML="";
}
function DayGlow() {
	const InDay = document.getElementById('FavDay').value;

	switch(InDay) {
		case 'Monday':
		case 'Tuesday':
			document.getElementById('DayFav').innerHTML='Ugh!!';
  			break;
		case 'Wednesday':
			document.getElementById('DayFav').innerHTML='Hump Day!';
			break;
		case 'Thursday':
			document.getElementById('DayFav').innerHTML='Is that a light I see?';
  			break;
		case 'Friday':
			document.getElementById('DayFav').innerHTML="Yaayyy. TGIF!";
			break;
		case 'Saturday':
			document.getElementById('DayFav').innerHTML="Party time eh!";
	  		break;
		case 'Sunday':
			document.getElementById('DayFav').innerHTML="OK, honeymoon's over";
			break;
		default:
			document.getElementById('DayFav').innerHTML="Say what?";
	}
}
</script>

As you can see, it allows you to choose an action depending on the input, similar to an 'if / else' block of code, with perhaps a bit less code - several 'cases' can be managed together. Note that the equality check is case-sensitive for strings.

View the source code to see the HTML, CSS and JavaScript coding.

It is not a popular conditional choice, but may suit your purposes. More info is available here.