0

I'm quite new at this and have a lot to learn. I'm using the Switch statement in this piece of JavaScript but I'm not getting the expected output as per the document.write lines. Any help, comments and suggestions are appreciated. - Thank you!

            <script type="text/javascript">

            var myAge = Number(prompt("Enter your age", 30));
            myAge = parseInt(myAge);

            switch (myAge)
            {
                case (myAge  >= 0 && myAge <= 10):
                    document.write("myAge is between 0 and 10");
                    break;

                case (!(myAge >= 0 && myAge <=10)):
                    document.write ("myAge is NOT between 0 and 10 <br />");
                    break;

                case (myAge >= 80 || myAge <= 10):
                    document.write ("myAge is 80 or above OR 10 or below <br />");
                    break;

                case (myAge >= 30 && myAge <=39 || (myAge >= 80 && myAge <= 89)):
                    document.write("myAge is between 30 and 39 or myAge is between 80 and 89");
                    break;

                default:
                    document.write("You did not enter a number.  Please enter a number.");
                    break;
            }       

            document.write("<BR>Execution continues here");


        </script>

This is what I wrote just using the 'if'.

        <script type="text/javascript">

        var myAge = Number(prompt("Enter your age", 30));

        if (myAge  >= 0 && myAge <= 10)
        {
            document.write ("myAge is between 0 and 10 <br />");
        }

        if (!(myAge >= 0 && myAge <=10))
        {
            document.write ("myAge is NOT between 0 and 10 <br />");
        }

        if (myAge >= 80 || myAge <= 10)
        {
            document.write ("myAge is 80 or above OR 10 or below <br />");
        }

        if (myAge >= 30 && myAge <=39 || (myAge >= 80 && myAge <= 89))
        {
            document.write("myAge is between 30 and 39 or myAge is between 80 and 89");
        }   


    </script>

This is the sample piece of code using 'switch' that I have to refer to.

<script type="text/javascript">

var secretNumber = prompt("Pick a number between 1 and 5:", "");
secretNumber = parseInt(secretNumber);

switch (secretNumber)
{
case 1:
   document.write("Too low!");
   break;

case 2:
   document.write("Too low!");
   break;

case 3:
   document.write("You guessed the secret number!");
   break;

case 4:
   document.write("Too high!");
   break;

case 5:
   document.write("Too high!");
   break;

default:
   document.write("You did not enter a number between 1 and 5.");
   break;
}
document.write("<BR>Execution continues here");

</script>
7
  • Condition into "cases", from where did you get this? Commented Oct 5, 2014 at 23:07
  • @GuilhermeNascimento You can check it here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 5, 2014 at 23:30
  • It's an assignment I'm working on and some is in the course material, the rest we write on our own. Commented Oct 5, 2014 at 23:34
  • ppl only need whats between the <script> tags otherwise your code needs to be scrolled :/ remove the rest Commented Oct 5, 2014 at 23:34
  • @BojanPetkovski you do not understand, what I meant is that he used conditions within the "CASE" and not within the "SWITCH", ie used in the wrong way "cases", so everyone will ALWAYS "boolean" Commented Oct 5, 2014 at 23:37

3 Answers 3

3

You need to rethink the logic in the case expression.

Let me make a substitution in your code, to illustrate the error

var test = myAge >= 0 && myAge <= 10;
if (test) {
   ...
} else if (!test) {
   ...
} else {
   // WILL NEVER BE RUN
}

If you want to use a switch statement you have to understand the types behind the data you're using.

true : Boolean
false : Boolean
9 : Number
1.0 : Number

In the example below, v must have the same type as value1 and value2.

switch(v)
{
   case (value1):
   ...       
   case (value2):
   ...
}

The issue is the following types don't match in your example.

v = Number
value1 = Boolean
value2 = Boolean
Sign up to request clarification or add additional context in comments.

6 Comments

Hi and thanks! I completed the first part of using 'if' and we have to re-write it just using 'switch'.
My answer addressed an issue with your logic, while the answer below addressed an issue with even using a switch statement correctly in the first place. You're question could have been more clear by saying, JS is complaining and my code doesn't run. Otherwise, I'm not sure if you're issue is syntactic or a logical error. In each case of the switch you put a value to match on. If you're value in this scenario is a boolean, then you can only match on the two types of booleans (true/false), or you could match on numbers for every possible number.
Hi, thank you for the tip on posting what the problem is and what's happening or isn't happening. The only direction I was given was: "Transform the multi-condition if statements code (which is the second block of code I added above), into a switch code (which is the first block I added that isn't working. I assumed I needed to match on different numbers based on the user input and the ranges established in the code.
I understand what you're saying. In the sample code I have to refer to it fits exactly what you are saying and I don't know how to transform the one with the ages to the sample switch code.
There are two ways, Boolean or Number each has a nightmarish implementation. Try both.
|
1

for conditions like this, use if:

if (myAge  >= 0 && myAge <= 10){
    document.write("myAge is between 0 and 10");

}else if (!(myAge >= 0 && myAge <=10)){
    //...
}

switch is for multiple exactly values, that isn't your situation:

switch(myAge){
    case 0:
        document.write("myAge is *exactly* 0");
        break;
    //...
}

6 Comments

Thank you. We've been asked to take what we wrote using 'if' and transform it into code using 'switch'. So if I understand what you said, my values need to be exact and not like the ranges I have in my attempt?
you should have written something simple in the first place then :p
We are told what code to write so I don't have a choice. I understand the if in the sample I was given and understand the switch in the sample I was given but don't understand how to transform the if to a switch when it's not apples to apples.
@Christine we all started at the beginning, im sure you'll get there if you are inquisitive and want to :)
I'm trying and I know eventually it will make sense. It's great having people here to help!
|
1

You can make a switch that will evaluate only the true statements, it fill find the first true statement (case) if any, or it will show the default. It will use conditional logic to work. So your code to work just add true instead of myAge

var myAge = Number(prompt("Enter your age", 30));

switch (true) {
    case (myAge >= 0 && myAge <= 10):
        document.write("myAge is between 0 and 10");
        break;

    case (!(myAge >= 0 && myAge <= 10)):
        document.write("myAge is NOT between 0 and 10 <br />");
        break;

    case (myAge >= 80 || myAge <= 10):
        document.write("myAge is 80 or above OR 10 or below <br />");
        break;

    case (myAge >= 30 && myAge <= 39 || (myAge >= 80 && myAge <= 89)):
        document.write("myAge is between 30 and 39 or myAge is between 80 and 89");
        break;

    default:
        document.write("You did not enter a number.  Please enter a number.");
        break;
}

Just a note that using switch like this is a performance overkill. It is better/faster to use if / else statements.

You can read more about switch here Switch and at the bottom you can see this method used (Method two).

3 Comments

Hi, I did try this earlier but because it only addresses the true statements I don't know if it is how we are to complete the assignment. The instructor is asking us to take the code using if and transform it using switch.
There is no other way for your switch to work with conditional tags :) Also with if/ else you are checking true/false statements :) It's the same logic implemented :)
When using the 'if' code and the number 5 for the age it returns "myAge is between 0 and 10" and "myAge is 80 or above OR 10 or below" as 5 fits both of those. However, using the above with the switch it only returns "myAge is between 0 and 10". If I understand correctly this is to do with the 'break'. How can I have it read the rest of the code to see if the number 5 fits any other conditions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.