I'm trying this simple code and seems like the user's input is not going through all the comparisons and jumps to the default one right away. I'm guessing that JS is taking the user's input as a string instead. I did try to parseInt() but didn't work. Here is my code;
var number = prompt('What\'s your favority number?');
switch(number){
case (number < 10):
console.log('Your number is to small.');
break;
case (number < 100):
console.log('At least you\'re in the double digits.');
break;
case (number < 1000):
console.log('Looks like you\'re in three digits.');
break;
default:
console.log('Looks like you\'re in the fouth digits.');
}
Use true as an expression for switch.
The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.[Ref]
A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using strict comparison, ===) and transfers control to that clause, executing 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.) . If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements.
var number = prompt('What\'s your favority number?');
number = Number(number); //Use `Number` to cast it as a number
switch (true) {
//----^^^^
case (number < 10):
console.log('Your number is to small.');
break;
case (number < 100):
console.log('At least you\'re in the double digits.');
break;
case (number < 1000):
console.log('Looks like you\'re in three digits.');
break;
default:
console.log('Looks like you\'re in the fouth digits.');
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Edit: As suggested by #bergi in the comments, an if/else cascade is the best approach for this problem.
var number = prompt('What\'s your favority number?');
number = Number(number); //Use `Number` to cast it as a number
if (number < 10)
console.log('Your number is to small.');
else if (number < 100)
console.log('At least you\'re in the double digits.');
else if (number < 1000)
console.log('Looks like you\'re in three digits.');
else
console.log('Looks like you\'re in the fouth digits.');
You're not understanding how the switch statement works. It is not a shortcut for checking dynamic values. It's a shortcut for checking known values.
Each case is a statement that gets evaluated to a value. If you look at the docs, you'll see that they have case: value, rather than what you are attempting, which is case: (expression). So, it's going to turn all your expressions into values.
So, for example, your first case is:
case (number < 10):
But what that really becomes is:
case false:
And of course, no number will evaluate to false (technically 0 is a falsey value, but the switch uses === comparison rather than == so 0 === false // false). Thus, all your cases are really case false, and so the switch is falling through all of them and landing on the default case.
So, for your situation, the switch statement is inappropriate. You should use if statements.
if(number < 10) {
} else if(number < 100) {
} else if(number < 1000) {
} else {
}
The switch statement is only appropriate when you know the values:
switch(number) {
case 10:
break;
case 100:
break;
case 1000:
break;
default:
}
(And yes, use parseInt to ensure you have integers.)
Related
This question already has answers here:
Switch case with conditions
(8 answers)
Closed 2 years ago.
var age = 16;
switch (true) {
case age < 16:
console.log("is a boy, he only drinks juice");
break;
case age >= 16 && age <= 20:
console.log("he can drink beer now ");
break;
default:
console.log("This is not working");
}
var age = 13;
switch (age) {
case age < 16:
console.log("is a boy, he only drinks juice");
break;
case age >= 16 && age <= 20:
console.log("he can drink beer now ");
break;
default:
console.log("This is not working");
}
why the second switch is not working ? and the first one works and how is it possible to make the second switch work ?
switch-case compares equality between the value resulted in the expression and the values defined as cases.
In your first statement the expression is true which is the value you want to compare, so the cases should be case true and case false.
In your code to wrote 'age>=16' etc... These are actually values of true or false, therefore the value in the switch can be compared to the cases.
In your second statement, you try to compare age which is an integer, with cases that are booleans, therefore, no case will be hit.
In your case, switch-case statement isn't suitable to your propose (you can use if-else)
This question already has answers here:
javascript switch(true)
(5 answers)
Closed 5 years ago.
Good afternoon!
Why does the first option work - switch (true), and the second option does not work - switch (a)?
First:
var a= prompt('Enter value', '');
switch(true)
{
case a>10:
alert('a>10');
break;
case a<10:
alert('a<10');
break;
default:
alert('a===10');
Second:
var a= prompt('Enter value', '');
switch(a)
{
case a>10:
alert('a>10');
break;
case a<10:
alert('a<10');
break;
default:
alert('a===10');
Why does the first option work - switch (true), and the second option
does not work - switch (a)?
As per documentation
The switch statement evaluates an expression, matching the
expression's value to a case clause, and executes statements
associated with that case.
So, in your first option true will match to either a < 10 or a > 10, however in second option, a being a string may not match to either of them.
Edit: I just realize OP ask for the difference instead of why it won't work, sorry for misunderstanding the question
It should work nicely
var a = prompt('Enter value', '');
switch (true) {
case (a > 10):
alert("a > 10");
break;
case (a < 10):
alert("a < 10");
break;
default:
alert('a == 10');
}
It's because a > 10 is true, like the switch(true), while switch(a) was passed a, which is not true. Of course, you should cast a. a = +a or use parseInt() or parseFloat().
Here's what you probably meant to do:
var a = prompt('Enter value');
if(+a > 10){
alert('a > 10');
}
else if(a !== '' && +a < 10){
alert('a < 10');
}
else if(+a === 10){
alert('a === 10');
}
else{
alert('Really, you should avoid using prompt and alert!');
}
// notice this is less code than that pointless switch
You need to convert the user input from a string to an integer, like so
a = parseInt(a)
Can anyone explain to me why first one is not working and second one is working?
First Statement
function test(n) {
switch (n) {
case (n == 0 || n == 1):
console.log("Number is either 0 or 1");
break;
case (n >= 2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");
}
}
Second Statement
function test(n) {
switch (true) {
case (n == 0 || n == 1):
console.log("Number is either 0 or 1");
break;
case (n >= 2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");
}
}
The parameter which is given to the switch will be compared using ===. In cases which you have, you have expressions which result to boolean type: n==0 || n==1 or n >= 2. When you pass a number , it tries to compare your number with a result given from the expression in cases. So for example with the given number 1 it tries to compare 1 === (1 == 0 || 1 == 1) -> 1 === true which returns false (strict comparison). So you get the Default text every time.
For the first case, you need to have numbers in the cases of your switch , not a boolean (n==0 || n==1 results to boolean).
With the second case, you have in the switch value true of type boolean.When you pass again 1 the comparing goes like true === (1 == 0 || 1 == 1) -> true === true and it returns true. So you get the desired result according to your value n. But the second case has no goals with using true as the value. You can replace it with a if else if statement.
If you want to get the same result for many cases you need to write 2 cases above each other. See this
case 0:
case 1:
result
Here the cases have type number, not boolean.
Code example.
function test(n){
switch (n) {
case 0:
case 1:
console.log("Number is either 0 or 1");
break;
case 2:
console.log("Number is 2")
break;
default:
console.log("Default");}
}
test(0);
test(1);
test(2)
switch is shorthand for a bunch of ifs.
switch(n) {
case x:
a();
break;
case y:
b();
break;
}
... is equivalent to:
if(n == x) {
a();
} else if(n == y) {
b();
}
So your first piece of code:
switch (n) {
case (n==0 || n==1):
console.log("Number is either 0 or 1");
break;
case (n>=2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");}
}
... is equivalent to:
if(n == (n==0 || n==1)) {
console.log("Number is either 0 or 1");
} else if ( n == ( n >= 2)) {
console.log("Number is greater than 1");
} else {
console.log("Default");
}
I hope you can see that n == (n==0 || n==1) and n == ( n >= 2) are both nonsense. If n is 0, for example, the first will evaluate to 0 == true. In many languages this will cause a compiler error (comparing different types). I don't especially want to think about what it does in Javascript!
Your second example:
switch (true) {
case (n==0 || n==1):
console.log("Number is either 0 or 1");
break;
case (n>=2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");
}
Is equivalent to:
if(true == (n==0 || n==1)) {
console.log("Number is either 0 or 1");
} else if(true == (n>=2)) {
console.log("Number is greater than 1");
} else {
console.log("Default");
}
... in which at least the condition statements true == (n==0 || n==1) and true == (n >=2) make sense.
But this is an unconventional way to use switch in most languages. The normal form is to use the value you're testing as the parameter to switch and for each case to be a possible value for it:
switch(n) {
case 0:
case 1:
console.log("n is 0 or 1");
break;
case 2:
console.log("n is 2);
break;
default:
console.log("n is some other value");
}
However switch doesn't provide a cleverer case than a full equality check. So there's no case >2 && <5.
Your can either use your trick using switch(true) (in Javascript -- there are many languages in which this won't work), or use if/else.
switch uses strict comparison.
You take a number in the switch statement and in cases, just comparsions which return a boolean value.
A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using strict comparison, ===) and transfers control to that clause, executing 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.) If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.
New to JavaScript so please forgive me if this has an obvious answer. I'm trying to get a switch statement to output a specific phrase depending on the value of an input box, however it will only output the default option. What have I done wrong? Thanks.
<input id="inputIQ" type="number"/>
<button onclick="inputIQFunction()">Submit</button>
<script>
function inputIQFunction()
{
var userinput = document.getElementById("inputIQ").value;
switch (userinput) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
}
</script>
Basically, switch doesn't support conditional expressions. It just jumps to the value according to the cases.
If you put true in the switch (true) part, it'll jump to the case whose have true value.
Try like this
switch (true) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
You cannot use logical conditions in your switch statement. It actually compares your userinput to a result of condition (true \ false), which never occurs.
Use conditions instead:
function inputIQFunction() {
function getIQFunctionOutput(inputValue) {
var parsedInput = parseInt(inputValue);
if (Number.isNaN(parsedInput))
return "Please, enter a correct value";
return parsedInput <= 10
? "Less or equal than 10"
: "Greater than 10";
}
var userinput = document.getElementById("inputIQ").value;
var output = getIQFunctionOutput(userinput);
alert(output);
}
<input id="inputIQ" type="number" />
<button onclick="inputIQFunction()">Submit</button>
P.S. You can actually use switch with logical statements this way:
switch (true) {
case userinput <= 10:
break;
case userinput > 10:
break;
}
but I would highly recommend not to use this approach because it makes your code harder to read and maintain.
Try like this:
<input id="inputIQ" type="number"/>
<button onclick="inputIQFunction()">Submit</button>
<script>
function inputIQFunction() {
var userinput = document.getElementById("inputIQ").value;
userinput = parseInt(userinput);
switch (true) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
}
</script>
A switch works by testing the value of the expression in switch(expression) against the values of each case until it finds one that matches.
In your code, the userinput in switch(userInput) is a string, but your two case statements both have a value of either true or false. So you want to use switch(true) - that's how you get a switch to work with arbitrary conditions for each case. In context:
switch(true) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
I know this is an old thread but I'm just starting out on JS (one week in) and this is the simplest thing I could create just so the logic is understood.
Switch appears to work only by true/false when using a user input value.
My script looks like:
<script>
document.getElementById("click").onclick = function () {
var day = document.getElementById("day").value;
switch (true) {
case day == 1:
document.write("Monday");
break;
case day == 2:
document.write("Tuesday");
break;
default:
document.write("Please enter valid number")
}
</script>
Like I said I'm only a week into this but I'm making a small portfolio for myself with these little things that courses may not teach, I'm open to any one wishing to offer me help learning also, hope it helps with understanding the logic.
You are not fulfilling the requirements of 'switch & case'
userinput <= 10:
It means 'true'
because '<=' is a comparison operator. It compares 'userinput' and ’10'(given value) and give you an answer in boolean(i.e. true or false).
But, here in switch case you need an integer value.
Another
You have entered this
'switch (userinput)' here 'switch' considering 'userinput' a string that should be integer,
You can fix it with this.
switch (eval(userinput))
I have the following switch block:
var str = 'matches[pw1]';
switch (str)
{
case (str.indexOf('matches') > -1) :
console.log('yes');
break;
default:
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
What I want is, that if str contains the word 'matches', then it should run the first case block, otherwise the default block.
However when I run this, the output I get is '0', and then 'no', meaning the default block is running despite the conditions for the first case being met.
Any ideas what's wrong?
Your case is likely testing whether (str.indexOf('matches') > -1) == str.
EDIT:
It might be valuable to understand exactly what switch and case mean. One of Javascript's ancestors, C, commonly used switch to replace blocks of code where a primitive was being compared against a list of values (often from an enumeration, or a series of literals). So instead of:
if (type == ENABLE_FRAMISTAN)
{
enable_framistan();
}
else if (type == ENABLE_FROBSOSTICATOR)
{
enable_frobnosticator();
}
else if (type == DISABLE_BAZTICULATOR)
{
disable_bazticulator();
}
else
{
assert(false);
}
you could instead write:
switch (type)
{
case ENABLE_FRAMISTAN: enable_framistan(); break;
case ENABLE_FROBNOSTICATOR: enable_frobnosticator(); break;
case DISABLE_BAZTICULATOR: disable_bazticulator(); break;
default: assert(false); break;
}
...which might make it easier to digest (and or spot errors in) a large block of code which effectively mapped type values to functions being called (or some such). Your designated usage, checking to see whether a string matches any of a number of potential (exclusive with one another?) patterns, does not map as well to switch. If it were merely equality being tested, it would work well, but your condition is more sophisticated than switch was designed to express. Any way that you manage to preserve switch with your feature set will likely require less-than-obvious code.
Why not use an if statment? try something like this:
var str = 'matches[pw1]';
if(str.indexOf('matches') > -1) {
console.log('yes');
break;
}else{
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
It should work since you don't have alot of cases anyways. I don't think you can do a comparing in cases.
What I want is, that if str contains the word 'matches', then it should run the first case block, otherwise the default block.
You cannot do that with a switch statement. A switch statement compares the result of evaluating the switch expression (in this case str) with the values of the case labels. The case labels can be expressions (as in your example), but if they are the expressions are evaluated and then compared against the value above using ===. (That's what the ECMAScript 5.1 spec says ...)
So what your code is actually doing for that case is (roughly speaking):
evaluate (str.indexOf('matches') > -1) which gives you true or false
compare true or false with the value of str ... which fails and the case body isn't executed.
Now I think you could make your approach work as follows:
case (str.indexOf('matches') > -1 ? str : '') :
console.log('yes');
break;
but that stinks from a code readability perspective (IMO).
You could do this:
console.log( str.indexOf( 'matches' ) > -1 ? 'yes' : 'no' );
You should know the basic usage of switch. I think you mistakenly use Switch. Try to use it as following:
var str = 'matches[pw1]';
str = str.indexOf('matches');
switch (str)
{
case -1 :
console.log('yes');
break;
default:
console.log(str.indexOf('matches') ) ;
console.log('no');
break;
}
Please look at the Following URL http://www.w3schools.com/js/js_switch.asp
If the above is not suitable for your logic, use if.. else if ...
http://www.w3schools.com/js/js_if_else.asp