JavaScript Switch statement

JavaScript switch statement is used to do different actions based on different conditions.

Switch statement

Switch statement is used to select one block from available blocks

Syntax

switch(expression) {
    case value1:
        //Statements executed when the result of expression is value1
        break;
    case value2:
        //Statements executed when the result of expression is value2
        break;
    default:
        //Statements executed when the result of expression not match with any cases
}

The switch statement will executes as follows:

The expression is evaluates first. The expression value is matched with each cases, if the value is matched the statements for that case is executed. If no cases are matched than default case statements will be executes.

Example

<!DOCTYPE html>
<html>
<body>


<p id="text">Fruit color</p>

<script>
document.getElementById('text').innerHTML = '<br >' +getFruitColor('Orange');
document.getElementById('text').innerHTML += '<br >' +getFruitColor('Banana');
document.getElementById('text').innerHTML += '<br >' +getFruitColor('Pinapple');


function getFruitColor(fruit) {
	var msg;
	switch(fruit) {
		case 'Orange':
			msg = 'Orange is of orange color';
			break;
		case 'Applie':
			msg = 'Apple is of red color';
			break;
		case 'Banana':
			msg = 'Banana is of yellow color';
			break;
		default:
			msg = 'Fruit is not available';
	}
	
	return msg;
}

</script>

</body>
</html>

Download the code Run the code

break keyword

When a JavaScript found a break statement, the switch statement execution stops from where it reached and returns next statement after switch.

When a match is found from available cases, there is no need to check further cases for matches

It is not necessary to have a code block for every cases in switch statement. In such cases more than one switch cases can have same code blocks.

<!DOCTYPE html>
<html>
<body>


<p id="text">Fruit color</p>

<script>
document.getElementById('text').innerHTML = '<br >' +getFruitColor('Orange');
document.getElementById('text').innerHTML += '<br >' +getFruitColor('Banana');
document.getElementById('text').innerHTML += '<br >' +getFruitColor('Pinapple');


function getFruitColor(fruit) {
	var msg;
	switch(fruit) {
		case 'Orange':
			msg = 'Orange is of orange color';
			break;
		case 'Apple':
		case 'Strawberry':
			msg = 'Apple & Strawberry are of red color';
			break;
		case 'Banana':
			msg = 'Banana is of yellow color';
			break;
		default:
			msg = 'Fruit is not available';
	}
	
	return msg;
}

</script>

</body>
</html>

Download the code Run the code

The default case is used to specify a code block if no match is found from available cases. default case is not mandatory and can be omitted. default case is always the last case of a switch statement and can not contain a break statement.

<<< JavaScript ConditionsJavaScript For loop >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .