Why does the below code not print anything? - javascript

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.

Related

Syntax error resulting from invalid syntax in if / else statements

// Check if the user is ready to play!
confirm("Are you ready to play?");
var age = prompt("What's your age");
if ( age is less than 13)
{
console.log("You are allowed to play,but we take no responsibility");
}
else {
console.log("Go on! you can play");
}
I've got a syntax error while executing this JavaScript code, the first two lines (confirm and variable) are correct, this error is somewhere in the if / else satements.
Use < operator instead of is less than
// Check if the user is ready to play!
confirm("Are you ready to play?");
var age = prompt("What's your age");
if (age < 13) {
alert("You are allowed to play, but we take no responsibility");
} else {
alert("Go on! you can play");
}
You can reduce line of code also by using ternary operator
age < 13 ? console.log("You are allowed to play, but we take no responsibility"):console.log("Go on! you can play");

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.

Simple switch statement

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>

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