Nested switch statement in javascript - javascript

Is it possible to use nested switch statement in javascript.
My code is some what look like
switch(id1)
{
case 1:
switch(id2){
case 1:{
switch(id3){
case 1:{}
case 2:{}
}
}
case 2:{
switch(id4){
case 1:{}
case 2:{}
}
}
}
case 2:
}
If yes then it is a good practice to do or we can use any alternate approach.

Your approach is absolutely fine.
You can make the switch nesting less complex by using switch (true):
switch (true) {
case ((id1 === 1) && (id2 === 1) && (id3 === 1)) :
case ((id1 === 1) && (id2 === 1) && (id3 === 2)) :
case ((id1 === 1) && (id2 === 2) && (id3 === 1)) :
case ((id1 === 1) && (id2 === 2) && (id3 === 2)) :
case ((id1 === 2) && (id2 === 1) && (id3 === 1)) :
case ((id1 === 2) && (id2 === 1) && (id3 === 2)) :
case ((id1 === 2) && (id2 === 2) && (id3 === 1)) :
case ((id1 === 2) && (id2 === 2) && (id3 === 2)) :
}

Yes, you can use inner switch like this way,
Please check this demo : https://jsfiddle.net/1qsfropn/3/
var text;
var date = new Date()
switch (date.getDay()) {
case 1:
case 2:
case 3:
default:
text = "Looking forward to the Weekend";
break;
case 4:
case 5:
text = "Soon it is Weekend";
break;
case 0:
case 6:
switch(date.getFullYear()){
case 2015:
text = "It is Weekend of last Year.";
break;
case 2016:
text = "It is Weekend of this Year.";
break;
case 2017:
text = "It is Weekend of next Year.";
break;
default:
text = date.getDay();
break;
}
break;
}
document.getElementById("demo").innerHTML = text;`

You can use a nested switch statement but that can quickly become a spaghetti code and therefore it is not recommended. I would rather use functions with the nested switch statement for code clearance or maybe use recursive function depending on what the code is supposed to do.
This is only a pseudo-code but I hope it gives you some idea on how to implement it. You have to be carefull to make the recursion stop on some given value of the ID.
This pseudo-code increments the value of the ID by 1 if the value of the ID is 1, and increments by 2 if the value is 2. If the value is not 1 or 2 the recursion ends.
function recursiveSwitch(var id) {
switch(id) {
case 1:
recursiveSwitch(id + 1);
break;
case 2
recursiveSwitch(id + 2)
break;
default:
return;
}
}

Basically, it's possible but I think it depends on the complexity of the nesting if it's recommended to use nested switch statement or to use functions with the nested switch statement as Ómar Óskarsson has suggested.

Related

Why this switch isn't giving any output? [duplicate]

Am I writing the correct switch case with conditions?
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
alert('31');
break;
default:
alert('>41');
}
For some reason, the alert does not occur when the conditions are matched!
A switch works by comparing what is in switch() to every case.
switch (cnt) {
case 1: ....
case 2: ....
case 3: ....
}
works like:
if (cnt === 1) ...
if (cnt === 2) ...
if (cnt === 3) ...
Therefore, you can't have any logic in the case statements.
switch (cnt) {
case (cnt >= 10 && cnt <= 20): ...
}
works like
if (cnt === (cnt >= 10 && cnt <= 20)) ...
and that's just nonsense. :)
Use if () { } else if () { } else { } instead.
You should not use switch for this scenario. This is the proper approach:
var cnt = $("#div1 p").length;
alert(cnt);
if (cnt >= 10 && cnt <= 20)
{
alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
alert('31');
}
else
{
alert('>41');
}
This should work with this :
var cnt = $("#div1 p").length;
switch (true) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
break;
default:
alert('>41');
}
Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.
Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.
$('.next').click(function(){
var imageToSlide = $('#imageSprite'); // Get id of image
switch(true) {
case (imageToSlide.hasClass('pos1')):
imageToSlide.removeClass('pos1').addClass('pos2');
break;
case (imageToSlide.hasClass('pos2')):
imageToSlide.removeClass('pos2').addClass('pos3');
break;
case (imageToSlide.hasClass('pos3')):
imageToSlide.removeClass('pos3').addClass('pos4');
break;
case (imageToSlide.hasClass('pos4')):
imageToSlide.removeClass('pos4').addClass('pos1');
}
}); `
What you are doing is to look for (0) or (1) results.
(cnt >= 10 && cnt <= 20) returns either true or false.
--edit--
you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length.
--edit--
function date_conversion(start_date){
var formattedDate = new Date(start_date);
var d = formattedDate.getDate();
var m = formattedDate.getMonth();
var month;
m += 1; // JavaScript months are 0-11
switch (m) {
case 1: {
month="Jan";
break;
}
case 2: {
month="Feb";
break;
}
case 3: {
month="Mar";
break;
}
case 4: {
month="Apr";
break;
}
case 5: {
month="May";
break;
}
case 6: {
month="Jun";
break;
}
case 7: {
month="Jul";
break;
}
case 8: {
month="Aug";
break;
}
case 9: {
month="Sep";
break;
}
case 10: {
month="Oct";
break;
}
case 11: {
month="Nov";
break;
}
case 12: {
month="Dec";
break;
}
}
var y = formattedDate.getFullYear();
var now_date=d + "-" + month + "-" + y;
return now_date;
}
Switch case is every help full instead of if else statement :
switch ($("[id*=btnSave]").val()) {
case 'Search':
saveFlight();
break;
case 'Update':
break;
case 'Delete':
break;
default:
break;
}
Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.
What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.
Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.
Like follow:
switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
alert('10');
break;
case (cnt >= 21 && cnt <= 30 && cnt):
alert('21');
break;
case (cnt >= 31 && cnt <= 40 && cnt):
alert('31');
break;
default:
alert('>41');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>

Javascript - Rock, Paper, scissors with switch statement? If not what are alternatives?

I am running the following codes bellow it only prints 'Draw!' the other cases does not work, what am I doing wrong?
const rps = (p1, p2) => {
var s = 'scissors';
var p = 'paper';
var r = 'rock';
var ans = '';
switch (rps) {
case (p1 == p && p2 == r):case (p1 == s && p2 == p): case (p1 == r && p2 == s):
ans = ('Player 1 won!');
break;
case (p1 == s && p2 == r): case (p1 == r && p2 == p): case (p1 == p && p2 == s):
ans = ('Player 2 won!');
break;
default: ans = ('Draw!');
break;
}
return ans
}
rps('paper','scissors')
switch compares the value you put in (rps which is a function) with each case (which will be true or false).
Since the function never matches a boolean, you always end up hitting the default case.
what am I doing wrong?
Trying to use switch for something it isn't really suited to.
Use if and else instead.
let rock = 2;
let scissors = 4;
let paper = 8;
let firstPlayerChoice = rock;
let secondPlayerChoice = paper;
switch (firstPlayerChoice / secondPlayerChoice) {
case 1:
console.log('there is a tie! pick again');
break;
case 0.5:
case 4:
console.log(`first player won!`);
break;
case 2:
case 0.25:
console.log(`second player won!`);
break;
default:
console.log('something went wrong!');
}
¡Hello!,
You are misunderstanding the use of "switch", the switch works like this:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
Soruce: https://www.w3schools.com/js/js_switch.asp
Like Quentin says, use "if" instead

Simplifying this JavaScript-switch

I would like some advice on how to slim down this switch:
switch (lotUser | winningLot) {
case lotUser === winningLot[0]:
case lotUser === winningLot[1]:
case lotUser === winningLot[2]:
case lotUser === winningLot[3]:
case lotUser === winningLot[4]:
case lotUser === winningLot[5]:
case lotUser === winningLot[6]:
case lotUser === winningLot[7]:
console.log("You win!");
break;
default:
console.log("You do not win!");
break;
}
Instead of
case lotUser === winningLot[0]:
I wrote the script to be:
switch (lotUser | winnendLot) {
case lotUser === winnendLot[0|1|2|3|4|5|6|7]:
console.log("You win!");
break;
default:
console.log("You do not win!");
break;
}
I just don't know if this works the way I want it to work. It needs to check if the generated lotUser is equal to one of the values in an array (winningLot). If the lotUser equals one or more of the values in the winningLot array, it should output "You win!".
Could someone please confirm that my code does the description I gave?
What about Array.prototype.indexOf()?
if (winnedLot.indexOf(lotUser) !== -1) {
console.log("Won!");
}
else {
console.log("Lost!");
}
It searches the array for the first occurrence of the value stored in lotUser and returns its respective index.
Since you do not need to count the occurrences, this should be the best way.
If you want to count them, use a loop:
var count = 0;
for (var i=0, len=winnedLot.length; i<len; i++) {
if (winnedLot[i] === lotUser) {
count++;
}
}
You can simply use indexOf:
if(winningLot.indexOf(lotUser) >= 0) {
...
} else {
...
}
Well for starters you're using switch incorrectly. The value to compare goes in the switch(...) part, and the possible values are listed by each case ...:
Anyway, that aside, all you want is to check if lotUser is in the winnendLot array. Easy:
// assuming supporting browser:
if( winnendLot.indexOf(lotUser) > -1) console.log("You win!");
// full browser support:
var winner = false, l = winnendLot.length, i;
for( i=0; i<l; i++) {
if( winnendLot[i] === lotUser) {
winner = true;
break;
}
}
if( winner) console.log("You won!");

Does switch statement start comparing cases from the top in this example?

I found this example to make range work with switch statement:
function GetText(value)
{
var result;
switch (true)
{
case ((value >= 26) && (value <= 50)):
result = ">= 26.";
break;
case ((value >= 1) && (value <= 25)):
result = "Between 1 and 25.";
break;
case (value == 0):
result = "Equals Zero.";
break;
}
return result;
}
But if I modify the code and remove the second check for the value the example will still work:
function GetText(value)
{
var result;
switch (true)
{
case ((value >= 26)):
result = ">= 26 .";
break;
case ((value >= 1)):
result = "Between 1 and 25.";
break;
case (value == 0):
result = "Equals Zero.";
break;
}
return result;
}
So if I passed 29 even that I have two true cases the first one will be selected. My question is that how switch statement works in most of programming languages it will start comparing from the top or its only in this case (and is it good or bad to write it like that?).
switch statement checks for matches from top to bottom.
From MDN docs on switch statement:
If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.
I would do something like this (with if and else if chains):
function GetText(value) {
var result;
if (value == 0) {
result = "Equals Zero.";
} else if (value <= 25) {
result = "Between 1 and 25.";
} else if (value <= 50) {
result = "Between 26 and 50.";
}
return result;
}

How do you Javascript charAt() a integer?

I have an array. One of the values in that array responses[1] is an integer. This integer can be from 1 to whatever number you want. I need to get the last number in the integer and determine based on that number if I should end the number with 'st', 'nd', 'rd', or 'th'. How do I do that? I tried:
var placeEnding;
var placeInt = response[1]; //101
var stringInt = placeInt.toString();
var lastInt = stringInt.charAt(stringInt.length-1);
if (lastInt == '1'){
placeEnding = 'st';
} else if (lastInt == '2'){
placeEnding = 'nd';
} else if (lastInt == '3'){
placeEnding = 'rd';
} else {
placeEnding = 'th';
}
but that did not work. Every time I tried printing placeEnding it was always 'th' no matter if it should have been 'st', 'rd', or 'nd'. When I tried printing placeInt, stringInt, or lastInt they all printed as " instead of the number. Why is this so? When I print responses[1] later on in the script I have no problem getting the right answer.
If all you want is the last digit, just use the modulus operator:
123456 % 10 == 6
No need to bother with string conversions or anything.
Here you go:
var ends = {
'1': 'st',
'2': 'nd',
'3': 'rd'
}
response[1] += ends[ response[1].toString().split('').pop() ] || 'th';
As others have pointed out, using modulus 10 is more efficient:
response[1] += ends[ parseInt(response[1], 10) % 10 ] || 'th';
However, this'll break if the number has a decimal in it. If you think it might, use the previous solution.
In my rhino console.
js> (82434).toString().match(/\d$/)
4
Alternate way to get lastInt is:
var lastInt = parseInt(stringInt)%10;
switch lastInt {
case 1:
placeEnding = 'st';
break;
case 2:
placeEnding = 'nd';
break;
case 3:
placeEnding = 'rd';
break;
default:
placeEnding = 'th';
}
I noticed I wanted to use the st/nd/rd/th in dates, and just noticed there is an exception between 10 and 20 with the eleventh, twelfth and so on, so I came to this conclusion:
if (n % 10 === 1 && (n % 100) - 1 !== 10) {
return "st";
} else if (n % 10 === 2 && (n % 100) - 2 !== 10) {
return "nd";
} else if (n % 10 === 3 && (n % 100) - 3 !== 10) {
return "rd";
}
return "th";

Categories