Simple switch statement - javascript

var speed = prompt("Do you know how to type?");
speed = speed.toLowerCase();
if (speed === "yes" ) {
var howFast = prompt("what is your wpm?(the answer must be a number between 1 and 200");
switch(howFast) {
case (howFast <= 10):
console.log("you are a snail! practice and type at least 20 wpm, then try this again.");
break;
case (howFast <= 30):
console.log("you are still pretty slow, but you're getting there!");
break;
case (howFast <= 50):
console.log("you are getting there, keep trying");
break;
case (howFast <= 90):
console.log("WoW! Excellent job! Your tenacity has paid off");
break;
case (howFast > 90):
console.log("you are a megaracer! congratulations!");
break;
default:
console.log("DOES NOT COMPUTE... You're either superfast or playing around!");
}
} else { alert("learn how to type and comeback.");}
I am trying to code a simple switch statement in javascript to ask users their typing speed. To my dismay, when this code executes the final alert i get back is always the default case. Please tell me what I did wrong!

just change:
switch(howFast) {
..
to
switch(true) {
..
and it should work.
Demo:: jsFiddle

I got this working :
var speed = prompt("Do you know how to type?");
speed = speed.toLowerCase();
if (speed === "yes" ) {
var howFast = prompt("what is your wpm?(the answer must be a number between 1 and 200");
switch(true) {
case (parseInt(howFast) <= 10):
console.log("you are a snail! practice and type at least 20 wpm, then try this again.");
break;
case (parseInt(howFast) <= 30):
console.log("you are still pretty slow, but you're getting there!");
break;
case (parseInt(howFast) <= 50):
console.log("you are getting there, keep trying");
break;
case (parseInt(howFast) <= 90):
console.log("WoW! Excellent job! Your tenacity has paid off");
break;
case (parseInt(howFast) > 90):
console.log("you are a megaracer! congratulations!");
break;
default:
console.log("DOES NOT COMPUTE... You're either superfast or playing around!");
}
} else { alert("learn how to type and comeback.");}
jsFiddle: http://jsfiddle.net/kR4cy/6/
Hope it helps

Its a bit of a hack but you can do expressions in JS case statements like this:
var wpm = parseInt(howFast); // convert string to number first
switch(true)
{
case wpm >= 0 && wpm <= 10:
console.log('snail');
break;
case wpm > 10 && wpm <= 30:
console.log('slowpoke');
break;
// etc.
}

In this case, there isn't an expression that applies to each case, therefore, an if-else block makes more sense to use instead of switch.

From my experience, you cannot have operators in your switch case; you must have a definite value. In this case you should use an IF ELSE block even though the switch would look better.
Edit: I also found this answer from a similar question.

You need to convert the prompt response to an integer before you compare it, and you will need to change your switch to a set of IFs.
<script>
var speed = prompt("Do you know how to type?");
var howFast;
var logMessage;
speed = speed.toLowerCase();
if (speed === "yes" ) {
howFast = parseInt(prompt("what is your wpm?..."));
logMessage = "DOES NOT COMPUTE... You're either superfast or playing around!";
if (howFast <= 10)
logMessage = "you are a snail! practice and type at least 20 wpm, then try this again.";
if (howFast <= 30)
logMessage = "you are still pretty slow, but you're getting there!";
if (howFast <= 50)
logMessage = "you are getting there, keep trying";
if (howFast <= 90)
logMessage = "WoW! Excellent job! Your tenacity has paid off";
if (howFast > 90)
logMessage = "you are a megaracer! congratulations!";
console.log(logMessage);
} else {
alert("learn how to type and comeback.");
}
</script>

Related

Why does the below code not print anything?

While I write switch(true) it produces the correct result, otherwise it does not produce any result. Why?
let age=18;
switch(age){
case age>18:
console.log("you can vote");
break;
case age<18:
console.log("you cannnot vote");
break;
}
The switch expression is a condition that can only work with equality == that's why it doesn't work in your case. you should use If-chains like this:
let age = 18;
if(age > 18)
{
console.log("you can vote");
}
else if(age < 18)
{
console.log("you can not vote");
}
The above code is the common solution for checking those types of conditions.

Switch statements in Javascript return the default every time, but not the cases [duplicate]

This question already has answers here:
JavaScript: using a condition in switch case
(13 answers)
Closed 2 years ago.
I was trying to solve the problem Conditionals 3 from the Mozilla Foundation website. The thing is, the activity asks to use only Switch statements inside the if(machineActive). I solved it using if-else, but once I tried to use the switch statement the console shows the default message I set, "Something must be wrong", no matter what value the score variable gets. Any time I change the cases just the default message is being shown.
What's the correct way to use switch statements in this case? The if-else is the most appropriate choice, but I want to stick with the task's rules this time.
let response;
let score = 75;
let machineActive = true;
if(machineActive) {
switch(score){
case (score<=100 && score>=90):
response = "What an amazing score! Did you cheat? Are you for real?";
break;
case (score<=89 && score>=70):
response = "That\'s a great score, you really know your stuff.";
break;
case (score<=69 && score>=40):
response = "You did a passable job, not bad!";
break;
case (score<=39 && score>=20):
response = "You know some things, but it's a pretty bad score. Needs improvement.";
break;
case (score<=19 && score>=0):
response = "That was a terrible score — total fail!";
break;
default:
response = "Something must be wrong";
}
} else {
response = 'The machine is turned off. Turn it on to process your score.';
}
the switch statement is used to determine if any of the cases equal the variable passed in. you are passing in a number, so none of your boolean cases will equal the number. you're going to want to pass in true and see if any cases evaluate to true.
A case clause used to match against expression. If the expression matches the specified valueN, the statements inside the case clause are executed until either the end of the switch statement or a break. from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Also, the cases are evaluated in order, and since you have breaks you don't need to check the upper end of the range on every case
switch (true) {
case score > 100:
response = "You definitely cheated. You must have gone to https://www.stackoverflow.com to get answers to all these questions."
break
case score >= 90:
response = "What an amazing score! Did you cheat? Are you for real?"
break
case score >= 70:
response = "That's a great score, you really know your stuff."
break
case score >= 40:
response = "You did a passable job, not bad!"
break
case score >= 20:
response =
"You know some things, but it's a pretty bad score. Needs improvement."
break
case score >= 0:
response = "That was a terrible score — total fail!"
break
default:
response = "Something must be wrong"
}
Change switch(score){ to switch(true){
It's trying to equate (score<=100 && score>=90) === score which it does not.
You need
switch (true) {
because you are checking against a boolean value.
By using score, the only part with
case score:
would work, because switch uses a strict comparison.
Then you could omit all parenteses and use a fall through by strating with filte for off values above, folloewd by smaller value and finally by having a default value for negative values.
let response;
let score = 75;
let machineActive = true;
if (machineActive) {
switch (true) {
case score > 100:
response = "Something must be wrong";
break;
case score >= 90:
response = "What an amazing score! Did you cheat? Are you for real?";
break;
case score >= 70:
response = "That\'s a great score, you really know your stuff.";
break;
case score >= 40:
response = "You did a passable job, not bad!";
break;
case score >= 20:
response = "You know some things, but it's a pretty bad score. Needs improvement.";
break;
case score >= 0:
response = "That was a terrible score — total fail!";
break;
default:
response = "Something must be wrong";
}
} else {
response = 'The machine is turned off. Turn it on to process your score.';
}
console.log(response);

switch statement to compare values greater or less than a number

I want to use the switch statement in some simple code i'm writing.
I'm trying to compare the variable in the parenthesis with values either < 13 or >= 13.
Is this possible using Switch?
var age = prompt("Enter you age");
switch (age) {
case <13:
alert("You must be 13 or older to play");
break;
case >=13:
alert("You are old enough to play");
break;
}
Directly it's not possible but indirectly you can do this
Try like this
switch (true) {
case (age < 13):
alert("You must be 13 or older to play");
break;
case (age >= 13):
alert("You are old enough to play");
break;
}
Here switch will always try to find true value. the case which will return first true it'll switch to that.
Suppose if age is less then 13 that's means that case will have true then it'll switch to that case.
Instead of switch you can easily to the same thing if else right?
if(age<13)
alert("You must be 13 or older to play");
else
alert("You are old enough to play");
This worked in my case:
var enteredAge = prompt("Enter your age");
let ageMoreThan13 = parseInt(enteredAge) >= 13;
let ageLessThan13 = parseInt(enteredAge) < 13;
switch (ageMoreThan13 || ageLessThan13) {
case ageLessThan13:
alert("You must be 13 or older to play");
break;
case ageMoreThan13:
alert("You are old enough to play");
break;
}
Instead of switch use nested if else like this:
if (x > 10) {
disp ('x is greater than 10')
}
else if (x < 10){
disp ('x is less than 10')
}
else
{
disp ('error')
}
You may use a conditional (ternary) operator instead. It takes a condition followed by a question mark (?), then an expression to execute if the condition is true and another if it is false.
This operator is frequently used as a shortcut for the if statement.
age >= 13 ? "You are old enough to play" : "You must be 13 or older to play";
It might be a bit silly to do this with a switch-case, but I added an answer where using switch-case, just for completeness.
var age = prompt("Enter you age");
switch (age) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
alert("You must be 13 or older to play");
break;
default:
alert("You are old enough to play");
break;
}

Switch Case not showing correct results

Here is my script
var marks = 11;
switch (marks) {
case (marks < 20):
console.log('Yes Freaking Failed');
break;
case (marks > 20):
console.log('Ahh Its Ok');
break;
case (marks > 80):
console.log('Whooping');
break;
default:
console.log('Cant say u maybe Flunked');
break;
}
I think it should display 'Yes Freaking Failed' because the marks are less than 20. But it shows 'Cant say u maybe Flunked'
Why is that?
When you write
switch (x) {
case(y):
...
}
it's equivalent to testing
if (x == y) {
...
}
So
case (marks < 20):
means:
if (marks == (marks < 20)) {
You can't use case for range tests like this, you need to use a series of if/else if:
if (marks < 20) {
console.log('Yes Freaking Failed');
} else if (marks < 80) {
console.log('Ahh Its OK');
} else {
console.log('Whooping');
}
Also notice that if it worked the way you thought, it could never execute marks > 80, because that would also match marks > 20, and the first matching case is always executed.
There's no need for the Cant say u maybe flunked case, because there are no other possibilities.
Technically it's not possible. Javascript makes it so.
If you need to compare, use if/else if/else.
Switch cases are for when you know you will have specific values.
var marks=11;
switch(marks){
case (11):
console.log('It would go in here');
break;
case (42):
console.log('If equal to 42');
break;
case (80):
console.log('if equal to 80.');
break;
default:
console.log('Cant say u maybe Flunked');
break;
}
Your code is equivalent to:
var marks=11;
switch(marks){
case (true):
console.log('Yes Freaking Failed');
break;
case (false):
console.log('Ahh Its Ok');
break;
case (false):
console.log('Whooping');
break;
default:
console.log('Cant say u maybe Flunked');
break;
}
marks is not true and is not false - so switch goes to default.
when you use switch statement, you are evaluating marks and compare the values of marks with the cases. And you have the following cases: 1, 0, 0, default. It's because (marks<20) evaluates to true which is 1, and the other two are false, which is 0.
So you should do if and else if in your case.

case user.length < 4; console.log("nametoo short :("); break; Why doesn't this work?

I'm working on switch statements and I've been trying to make this code right here work, but it doesn't seem to output the correct console.log case string.
var user = prompt("What is your name?").toLowerCase();
switch(user){
case "luka":
console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
break;
case user.length > 10:
console.log("That's a long name!");
break;
case user.length < 4:
console.log("Not to be rude or impolite to you in any way, but your name is kinda short :( Not that it isn't cool or something :D");
break;
}
I've tried putting paranthesis around the user like this (user).length < 4, but that doesn't work, nor some of my other tries. Does anybody know how to implement this correctly?
You should not use conditionals in a switch statement.
Use if/else if
var user = prompt("What is your name?").toLowerCase();
if (user==="luka") {
console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
} else if (user.length > 10) {
console.log("That's a long name!");
} else if (user.length < 4) {
console.log("Not to be rude or impolite to you in any way, but your name is kinda short :( Not that it isn't cool or something :D");
} else {
console.log("in else");
}
There is one possible workaround for using switch in the cases like yours:
var user = prompt("What is your name?").toLowerCase();
switch (true) {
case (user === "luka"):
console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
break;
case (user.length > 10):
console.log("That's a long name!");
break;
case (user.length < 4):
console.log("Not to be rude or impolite to you in any way, but your name is kinda short :( Not that it isn't cool or something :D");
}
However I'd follow #epascarello's advice and use if/else blocks.
That's just not how JavaScript switch statements work. The values in the "case" expressions are compared to the value of the switch expression.
The statement you have there is equivalent to:
if (user === "luka") {
console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
}
else if (user === (user.length > 10)) {
console.log("That's a long name!");
}
else if (user === (user.length < 4)) {
console.log("Not to be rude or impolite to you in any way, but your name is kinda short :( Not that it isn't cool or something :D");
}
Thus, you're comparing the value of "user" to the results of comparing user.length to those values. Those comparison results are boolean, so "use" will never be === to them.

Categories

Resources