switch is a good substitute for a nested if else statement. It has one parameter that accepts any value and that value will be compared strictly to a series of cases to find its equal. If there is an equal, it will run the block of that case until it finds a break keyword to stop it. If there is no break, it will run the next case under it until it finds the break keyword. But what if there is no equal in all the cases defined, then the default statement will run.
Syntax:
switch(variableName){
case 1: {
// statements;
break;
}
case 2: {
// statements;
break;
}
default: {
// statements;
}
}
Sample of using switch
=================
let x = Number(prompt("Enter any number: ", 1));
function displayingSumOfX(){
let sumOfX = 0;
switch(x){
case 1: {
sumOfX = 100;
}
case 2: {
sumOfX = sumOfX + x;
break;
}
case 3: {
sumOfX = 300;
}
case 4: {
sumOfX = sumOfX + 300;
break;
}
default: {
sumOfX = x;
}
}
return sumOfX;
}
=================
HTML
document.write(displayingSumOfX())
Result:
1
101
YOU ARE READING
Javascript Programming
RandomI am just documenting things what i learned online in here. I do express things in my own words. And I create my own program samples which serves as my practice. I do this so that when someday I would need some notes to review, I can just visit in h...
