Returning a value from switch statement

Returning a value from switch statement



I'm new to web development (JS) and I know there are many topics matching the title of mine, but no similar questions were answered, or maybe because I'm newbie, couldn't find.



In the code below I wanted my function and switch statements, to retrieve values from the arrays (bills) and in order to calculate new value, which to be assigned into a new non-existing place into the array tips. As a final result I want the function to return tips array with the value, depending on the case.


tips


tips



I know another way for solving this, anyway I was wondering whats wrong here, because that idea for solving it first came to my mind, and I thought it would work.


solving



Here is my code:


var tips = ;
var bills = [124, 48, 264];

function tipCalc(bills, tips)
switch(bills)
case bills < 50:
tips[0] = bills[1] * 0.2;
break;

case bills > 50:
tips[1] = bills[0] * 0.5;
break;

default:
console.log('no tips left.');

return tips;


tips = tipCalc(bills[0]);
console.log(tips);

enter code here





Use Array.push to add a new entry to an array in JavaScript, and use the return keyword to return a value or object.
– Dai
Sep 4 at 2:58


Array.push


return





This is not how switch works. bills is a number, bills < 50 and bills > 50 are booleans. They will never match. tips is undefined, since you never pass an argument for this parameter.
– Xufox
Sep 4 at 3:01



switch


bills


bills < 50


bills > 50


tips





What is bills < 50? And you use switch check bills = (bills < 50)
– Hongarc
Sep 4 at 3:04


bills < 50


bills = (bills < 50)





var tips = ; var bills = [124, 48, 264]; function tipCalc(bills) switch(true) case bills < 50: tips[0] = bills[1] * 0.2; break; case bills >= 50 && bills <= 200: tips[1] = bills[0] * 0.15; break; case bills > 200: tips[2] = bills[2] * 0.1; default: console.log('no tips left.'); return tips; console.log(tipCalc(bills[1]));
– Венелин Борисов
Sep 4 at 3:14






well thats my code for the moment, i dont know how to paste it again formatted btw.. so excuse me.. i understood that for the switch statement and matching types between switch and case.
– Венелин Борисов
Sep 4 at 3:16




3 Answers
3



Let's break this code down a bit and talk about what it's doing


var tips = ;
var bills = [124, 48, 264];



This part is declaring two variables in the global scope, which will both be accessible by any functions for both reading and writing (important - Google JS closures).


function tipCalc(bills, tips)
switch(bills)



You have now started a function which calls a switch to evaluate the value of bills. Because you are passing in bills[0], it will be evaluating bills[0] (124). It also accepts a second parameter called tips, which is undefined because no second argument is passed in when the function is called.


bills[0]


case bills < 50:
tips[0] = bills[1] * 0.2;
break;



This part is broken. If it was changed to an if statement, it would evaluate to false.


if


case bills > 50:
tips[1] = bills[0] * 0.5;
break;



Also broken. If changed to if statement, it would evaluate to true and be executed, but it would be performing an operation on undefined. If you didn't h have a second param also named tips, then you would be setting the global tips to 62.


if


tips


tips


default:
console.log('no tips left.');



This is the part that should currently be executed because it is the only one that can be true with the other two cases being structured incorrectly.


return tips;



Will return undefined because tips (within the scope of the function itself) began as undefined and has not been altered.


tips = tipCalc(bills[0]);
console.log(tips);
enter code here



Breaks the whole program, should be a comment with // at the beginning.


//



well, this is not good approach, but if it is required for you to use Switch you can try like this without bills array at all:


<script type="text/javascript">
var tips = ;



function tipCalc(bill)
switch (true)
case (bill < 50):
tips.push(bill * 0.2);
break;

case (bill > 50):

tips.push(bill * 0.5);
break;

default:
console.log('no tips left.');

return tips;


tipCalc(10);
for (let index = 0; index < tips.length; index++)
console.log(tips[index]);





</script>



Or in case you need to compare bills array and depends to the value insert to tips array i would make it like :


<script type="text/javascript">

var tips = ;
var bills = [124, 48, 264];

function tipCalc(bills)
for (let index = 0; index < bills.length; index++)

if (bills[index] <=50)
tips.push(bills[index] * 0.2);

else if (bills[index] >= 50)
tips.push(bills[index] * 0.5);

else
console.log("no tips left.");



tipCalc(bills);
for (let index = 0; index < tips.length; index++)
console.log(tips[index]);



</script>





The else clause can never be reached. Either it's <=50 or >=50, there are no other possibilities.
– Barmar
Sep 4 at 4:20


else


<=50


>=50





Barmar => damm miss it :) thank you for bug discovery and i already fix it
– Rostyslav Zhovnir
Sep 4 at 4:50



Here's a verbose way of doing what I think you want to do. (add up the tips total)




// create a blank tips array which we'll add to later
var tips = ;
// our bills array
var bills = [124, 48, 264];
// create a function that will calculate tips based on the bill totals
function calculateTips()
// create a counter that we will use to determine when we've reached the end of the loop
var forEachCounter = 0;
// for each will loop through each item in the bills array
bills.forEach(function(amount)
//this increases the counter by 1 on each loop
forEachCounter++;
switch(true)
case (amount <= 50):
// .push appends to the array
tips.push(amount * 0.2);
break;
case (amount > 50):
// amount is the value of the bill for this iteration * 0.5
tips.push(amount * 0.5);
break;

// if end of array has been reached
// bills.length = the total amount of array items in bills arrat
if (forEachCounter === bills.length)
// create a totalTips variable to add to
var totalTips = 0;
// create another counter to detect when end is reached
var forEachCounter2 = 0;
// loop through the tips array
tips.forEach(function(tipamount)
// add 1 to counter on each loop
forEachCounter2++;
// add to totalTips
// can also do totalTips = totalTips + tipamount;
totalTips += tipamount;
// when end of tip array is reached..
if (forEachCounter2 === tips.length)
//alert(totalTips);
// output it to where you need it
document.getElementsByTagName('body')[0].innerHTML = totalTips;

)

)

// call it when you need it
calculateTips();



note



If you're working with a lot of tips (like an entire national restaurant chain) you may want to consider using if/else instead of switch because switch is demonstrated to be slower with ranges



fiddle with it here



https://jsfiddle.net/Hastig/p1kfgreq/





thank u for the good alternative, but yet my exercise was to do the following, just with if-else/switch, function, and some arrays. Some of the lines from ur code im still not familiar with, anyway thank u. Ill look up to it.
– Венелин Борисов
Sep 4 at 4:22





@ВенелинБорисов I added annotations to the code to help you understand it. Good luck!
– Hastig Zusammenstellen
Sep 4 at 5:15



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)