How to use switch to compare values between values - javascript

I'm learning JavaScript with a very basic and simple Level Upper system by a button using a XP Table to set var named Level a value and print it.
How can I use the switch statement to compare numbers between 10 and 20 as example, and return a var named Level the value of 2(Lv. 2)?
I've tried using "case 10...20" (3 dots as in another languages) but it didn't work!
I tried to use if statement, but it doesn't work properly. :/
var Exp = 1;
var Level = 1;
function MaisExp()
{
Exp++;
document.getElementById("console").innerHTML = "+1 XP! | "+" Total: "+Exp+" xp points";
VerLevel();
}
function VerLevel()
{
switch(Exp)
{
case 0...10: ***< --- dots didn't work.***
{
Level=1;
}
case 20:
{
Level=2;
}
case 40:
{
Level=1;
}
case 80:
{
Level=1;
}
}
document.getElementById("tela").innerHTML = Level;
}

You can use if statements like this:
if(Exp >= 0 && Exp <= 10)
{
}
else if(Exp <= 20)
{
}
else if(Exp <= 30) etc...

The case statement doesn't work with multiple validations, it can only handle one per case. However, you can list multiple cases, for example:
switch(age){
case 0:// If age is 0, it would enter here, since there is no "break;" it goes down to 1
case 1:// Same as above
case 2:// Same as above
case 3:// Since this one has a break, this code is executed and then the switch terminates
console.log('This toy is not right for this person');
break;
default:// This special case fires if age doesn't match any of the other cases, or none of the other cases broke the flow
console.log('This toy is good for this person');
}
So, in your code, it should be something like:
switch(Exp)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
Level=1;
break;
case 20:
Level=2;
break;
case 40:
Level=1;
break;
case 80:
Level=1;
break;
}
But, since you want all to be level 1, but 20, you could also use the default case, like this:
switch(Exp)
{
case 20:
Level=2;
break;
default:
Level=1;
}

While you have already a default value of 1, you could take it in the function and check onle the condition for level = 2.
function VerLevel() {
Level = 1;
if (Exp === 20) {
Level = 2;
}
document.getElementById("tela").innerHTML = Level;
}
I suggest to change the style of variable and function to start with lower case letters, because functions with upper case letters denotes instanciable/constructor functions, which can be uses with new operator.

Related

Javascript switch statement check object keys [duplicate]

These two switch statements are the same, other than the use of console.log.
When outputting the result to the chrome console I get two different results.
The first one outputs:
this is the one
while the second outputs:
1
this is the one
Why is that?
const q = 1;
switch (q) {
case '1':
answer = "one";
case 1:
answer = 1;
case 2:
answer = "this is the one";
break;
default:
answer = "not working";
}
console.log(answer);
const q1 = 1;
switch (q1) {
case '1':
console.log("one");
case 1:
console.log(1);
case 2:
console.log("this is the one");
break;
default:
console.log ("not working");
}
I put a star(*) on the lines that executed.
The switches need breaks, or else one hit can execute multiple sections.
*const q = 1;
*switch (q) {
case '1':
answer = "one";
case 1:
* answer = 1;
case 2:
* answer = "this is the one"; //changed the value of answer
* break;
default:
answer = "not working";
}
*console.log(answer); //the first line of output.
*const q1 = 1;
*switch (q1) {
case '1':
console.log("one");
case 1: //where the hit occurred.
* console.log(1); // the second line of output.
case 2:
* console.log("this is the one"); //the third line of output.
* break;
default:
console.log ("not working");
}
This is because you are not using break; at the end of each case block. Use something like this:
const q = 1;
switch (q) {
case '1':
answer = "one";
break;
case 1:
answer = 1;
break;
case 2:
answer = "this is the one";
break;
default:
answer = "not working";
}
console.log(answer);
const q1 = 1;
switch (q1) {
case '1':
console.log("one");
break;
case 1:
console.log(1);
break;
case 2:
console.log("this is the one");
break;
default:
console.log ("not working");
}
break; just means that stop the execution here and don't move to the block below, just like in your case
A switch is not like a if/else if/ else. In an if structure it only runs the code in the block that follows it.
In a switch a case statement falls through to the next. If you do not want it to fall through you add a break.
function countDown(start) {
console.log('called with: ', start);
switch (start) {
case 3:
case 'three':
console.log(3);
case 2:
case 'two':
console.log(2);
case 1:
case 'one':
console.log(1);
}
}
countDown(3); // 3 2 1
countDown('two'); // 2 1
Now when you add a break it will not fall through
function countDown(start) {
console.log('called with: ', start);
switch (start) {
case 3:
case 'three':
console.log(3);
break;
case 2:
case 'two':
console.log(2);
break;
case 1:
case 'one':
console.log(1);
break;
}
}
countDown(3); // 3
countDown('two'); // 2
If we execute each line of code or verify each line code, you can see, in first switch case is executed case 1 and thencase 2, which makes value = this is the one now the break is executed and we are out of switch case 1.
Now,console.log(answer); hits and prints this is the one
Next, q1 =1
case 1:
console.log(1);
case 2:
console.log("this is the one");
Both of the above statement executes since, case 1 is correct match for switch case number 2, but there is no break so case 2 is also executed.
Hence, you see this output.
You can also refer these links also: Why is Break needed when using Switch?
https://javascript.info/switch
You need to add break to skip the next switch case.
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
conosle.log('case is 1 to 12');
break;
case 13:
console.log('case 13');
break;
const q = 1;
switch (q) {
case '1':
answer = "one";
case 1:
answer = 1;
case 2:
answer = "this is the one";
break;
default:
answer = "not working";
}
console.log(answer);
switch case default behaviour is that when a case will get true value then the following case statements will run without checking the condition . in this case case 1 is implemented as true so the next cases will not evaluate .
const q1 = 1;
switch (q1) {
case '1':
console.log("one");
case 1:
console.log(1);
case 2:
console.log("this is the one");
break;
default:
console.log ("not working");
}
in your second code , case 1 will evaluated as true so the compiler will not evaluate your case 2 . it will directly go to the case 2 block and console that until compiler find a break s

(JavaScript) Using a switch statement with an input box

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))

switch statemen t javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I made this code but it does not work at all
I am supposed to use the switch statement
Could you tell me please where is the error
thanks a loot :)
var side == parseInt(prompt('Enter a number of side between 3 and 10: '));
var shape ==['triangle','square','pentagon','hexagon','heptagon','octagon','nonagon','octagon'];
switch (shape){
case== 3:
shape=[0];
break;
case== 4:
shape==[1];
break;
case== 5:
shape==[2];
break;
case== 6:
shape==[3];
break;
case== 7:
shape==[4];
break;
case== 8:
shape==[5];
break;
case== 9:
shape==[6];
break;
case== 10:
shape==[7];
break;
}
alert('The shape is' + shape);
You are making an array shape=[0]; not referencing your array that has the values.
You have syntax errors galore:
case== 3:
should be just
case 3:
and
shape==[1];
== tests for quality, so you're basically saying shape is the same as an array containing the number 1.
You are using == when you should use =. In your switch you want to check on user input (side) and then case just need options no symbols. Finally shape needs to reassigned to the value from the array.
var side = parseInt(prompt('Enter a number of side between 3 and 10: '));
var shape =['triangle','square','pentagon','hexagon','heptagon','octagon','nonagon','octagon'];
switch (side){
case 3:
shape=shape[0];
break;
case 4:
shape=shape[1];
break;
case 5:
shape=shape[2];
break;
case 6:
shape=shape[3];
break;
case 7:
shape=shape[4];
break;
case 8:
shape=shape[5];
break;
case 9:
shape=shape[6];
break;
case 10:
shape=shape[7];
break;
}
alert('The shape is ' + shape);
Stop using == in place of =.
== is a comparison check, = is an assignment operator.
using switch:
var side = parseInt(prompt('Enter a number of side between 3 and 10')),
shapes = ['triangle','square','pentagon','hexagon','heptagon','octagon','nonagon','octagon'],
shape;
switch (side){
case 3:
shape = shapes[0];
break;
case 4:
shape = shapes[1];
break;
case 5:
shape = shapes[2];
break;
case 6:
shape = shapes[3];
break;
case 7:
shape = shapes[4];
break;
case 8:
shape = shapes[5];
break;
case 9:
shape = shapes[6];
break;
case 10:
shape = shapes[7];
break;
}
alert('The shape is ' + shape);
better way:
var side = parseInt(prompt('Enter a number of side between 3 and 10')),
shapes = ['triangle','square','pentagon','hexagon','heptagon','octagon','nonagon','octagon'];
alert('The shape is' + shapes[side - 3]);
You do not need a switch statement - you can have much shorter more concise code. You can just assign the shape, but make sure you check the prompted side is within range.
var shape = ['triangle','square','pentagon','hexagon','heptagon','octagon','nonagon','decagon'];
var side = parseInt(prompt('Enter a number of side between 3 and 10: '));
var userShape = shape[side - 3];
if (side < 3 || side > 10) {
alert('Not a recognised shape')
} else {
alert(userShape);
}
Unless you're sure you're not going to use the shape array again it's better to assign the result of checking the array to a new variable (here userShape) otherwise you're just overwriting the array.
Also, a ten-sided shape is a decagon :)
DEMO

Switch statement for multiple cases in JavaScript

I need multiple cases in switch statement in JavaScript, Something like:
switch (varName)
{
case "afshin", "saeed", "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows the DRY concept.
Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
}
This works in regular JavaScript:
function theTest(val) {
var answer = "";
switch( val ) {
case 1: case 2: case 3:
answer = "Low";
break;
case 4: case 5: case 6:
answer = "Mid";
break;
case 7: case 8: case 9:
answer = "High";
break;
default:
answer = "Massive or Tiny?";
}
return answer;
}
theTest(9);
Here's different approach avoiding the switch statement altogether:
var cases = {
afshin: function() { alert('hey'); },
_default: function() { alert('default'); }
};
cases.larry = cases.saeed = cases.afshin;
cases[ varName ] ? cases[ varName ]() : cases._default();
In Javascript to assign multiple cases in a switch, we have to define different case without break inbetween like given below:
<script>
function checkHere(varName){
switch (varName)
{
case "saeed":
case "larry":
case "afshin":
alert('Hey');
break;
case "ss":
alert('ss');
break;
default:
alert('Default case');
break;
}
}
</script>
Please see example click on link
I like this for clarity and a DRY syntax.
varName = "larry";
switch (true)
{
case ["afshin", "saeed", "larry"].includes(varName) :
alert('Hey');
break;
default:
alert('Default case');
}
If you're using ES6, you can do this:
if (['afshin', 'saeed', 'larry'].includes(varName)) {
alert('Hey');
} else {
alert('Default case');
}
Or for earlier versions of JavaScript, you can do this:
if (['afshin', 'saeed', 'larry'].indexOf(varName) !== -1) {
alert('Hey');
} else {
alert('Default case');
}
Note that includes won't work in some browser including older IE versions, but you could patch things up fairly easily. See the question determine if string is in list in javascript for more information.
My situation was something akin to:
switch (text) {
case SOME_CONSTANT || ANOTHER_CONSTANT:
console.log('Case 1 entered');
break;
case THIRD_CONSTANT || FINAL_CONSTANT:
console.log('Case 2 entered');
break;
default:
console.log('Default entered');
}
The default case always entered. If you're running into a similar multi-case switch statement issue, you're looking for this:
switch (text) {
case SOME_CONSTANT:
case ANOTHER_CONSTANT:
console.log('Case 1 entered');
break;
case THIRD_CONSTANT:
case FINAL_CONSTANT:
console.log('Case 2 entered');
break;
default:
console.log('Default entered');
}
Adding and clarifying Stefano's answer, you can use expressions to dynamically set the values for the conditions in switch, e.g.:
var i = 3
switch (i) {
case ((i>=0 && i<=5) ? i : -1):
console.log('0-5');
break;
case 6: console.log('6');
}
So in your problem, you could do something like:
var varName = "afshin"
switch (varName) {
case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
console.log("hey");
break;
default:
console.log('Default case');
}
Although it is so much DRY...
In Node.js it appears that you are allowed to do this:
data = "10";
switch(data){
case "1": case "2": case "3": // Put multiple cases on the same
// line to save vertical space.
console.log("small");
break;
case "10": case "11": case "12":
console.log("large");
break;
default:
console.log("strange");
break;
}
This makes for much more compact code in some cases.
I use it like this:
switch (true){
case /Pressure/.test(sensor):
{
console.log('Its pressure!');
break;
}
case /Temperature/.test(sensor):
{
console.log('Its temperature!');
break;
}
}
Some interesting methods. For me the best way to solve is using .find.
You can give an indication of what the multiple cases are by using a suitable name inside your find function.
switch (varName)
{
case ["afshin", "saeed", "larry"].find(firstName => firstName === varName):
alert('Hey');
break;
default:
alert('Default case');
break;
}
Other answers are more suitable for the given example but if you have multiple cases to me this is the best way.
It depends. Switch evaluates once and only once. Upon a match, all subsequent case statements until 'break' fire no matter what the case says.
var onlyMen = true;
var onlyWomen = false;
var onlyAdults = false;
(function(){
switch (true){
case onlyMen:
console.log ('onlymen');
case onlyWomen:
console.log ('onlyWomen');
case onlyAdults:
console.log ('onlyAdults');
break;
default:
console.log('default');
}
})(); // returns onlymen onlywomen onlyadults
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
You can use the 'in' operator...
It relies on the object/hash invocation, so it's as fast as JavaScript can be.
// Assuming you have defined functions f(), g(a) and h(a,b)
// somewhere in your code,
// you can define them inside the object, but...
// the code becomes hard to read. I prefer it this way.
o = { f1:f, f2:g, f3:h };
// If you use "STATIC" code can do:
o['f3']( p1, p2 )
// If your code is someway "DYNAMIC", to prevent false invocations
// m brings the function/method to be invoked (f1, f2, f3)
// and you can rely on arguments[] to solve any parameter problems.
if ( m in o ) o[m]()
You can do this:
alert([
"afshin",
"saeed",
"larry",
"sasha",
"boby",
"jhon",
"anna",
// ...
].includes(varName)? 'Hey' : 'Default case')
or just a single line of code:
alert(["afshin", "saeed", "larry",...].includes(varName)? 'Hey' : 'Default case')
a little improvement from ErikE's answer
I can see there are lots of good answers here, but what happens if we need to check more than 10 cases? Here is my own approach:
function isAccessible(varName){
let accessDenied = ['Liam', 'Noah', 'William', 'James', 'Logan', 'Benjamin',
'Mason', 'Elijah', 'Oliver', 'Jacob', 'Daniel', 'Lucas'];
switch (varName) {
case (accessDenied.includes(varName) ? varName : null):
return 'Access Denied!';
default:
return 'Access Allowed.';
}
}
console.log(isAccessible('Liam'));
The problem with the above approaches, is that you have to repeat the several cases every time you call the function which has the switch. A more robust solution is to have a map or a dictionary.
Here is an example:
// The Map, divided by concepts
var dictionary = {
timePeriod: {
'month': [1, 'monthly', 'mensal', 'mês'],
'twoMonths': [2, 'two months', '2 months', 'bimestral', 'bimestre'],
'trimester': [3, 'trimesterly', 'quarterly', 'trimestral'],
'semester': [4, 'semesterly', 'semestral', 'halfyearly'],
'year': [5, 'yearly', 'annual', 'ano']
},
distance: {
'km': [1, 'kms', 'kilometre', 'kilometers', 'kilometres'],
'mile': [2, 'mi', 'miles'],
'nordicMile': [3, 'Nordic mile', 'mil (10 km)', 'Scandinavian mile']
},
fuelAmount: {
'ltr': [1, 'l', 'litre', 'Litre', 'liter', 'Liter'],
'gal (imp)': [2, 'imp gallon', 'imperial gal', 'gal (UK)'],
'gal (US)': [3, 'US gallon', 'US gal'],
'kWh': [4, 'KWH']
}
};
// This function maps every input to a certain defined value
function mapUnit (concept, value) {
for (var key in dictionary[concept]) {
if (key === value ||
dictionary[concept][key].indexOf(value) !== -1) {
return key
}
}
throw Error('Uknown "'+value+'" for "'+concept+'"')
}
// You would use it simply like this
mapUnit("fuelAmount", "ltr") // => ltr
mapUnit("fuelAmount", "US gal") // => gal (US)
mapUnit("fuelAmount", 3) // => gal (US)
mapUnit("distance", "kilometre") // => km
// Now you can use the switch statement safely without the need
// to repeat the combinations every time you call the switch
var foo = 'monthly'
switch (mapUnit ('timePeriod', foo)) {
case 'month':
console.log('month')
break
case 'twoMonths':
console.log('twoMonths')
break
case 'trimester':
console.log('trimester')
break
case 'semester':
console.log('semester')
break
case 'year':
console.log('year')
break
default:
throw Error('error')
}
One of the possible solutions is:
const names = {
afshin: 'afshin',
saeed: 'saeed',
larry: 'larry'
};
switch (varName) {
case names[varName]: {
alert('Hey');
break;
}
default: {
alert('Default case');
break;
}
}
If your case conditions are complex, many case value matches, or dynamic value match required, then it may be best to move that case matching logic to handler child functions.
In your case, if say you had thousands of usernames to match against for a security permissions check for example, this method is cleaner option, more extensible, exposing the high level multi-way branch logic without getting swamped in a long list of case statements.
switch (varName)
{
case checkPatternAdministrator(varName):
alert('Hey');
break;
case checkPatternUserTypeA(varName):
alert('Hey2');
break;
case checkPatternUserTypeB(varName):
alert('Hey3');
break;
default:
alert('Default case');
break;
}
function checkPatternAdministrator(varName) {
// Logic to check Names against list, account permissions etc.
// return the varName if a match is found, or blank string if not
var matchedAdministratorName = varName;
return matchedAdministratorName;
}
Here is one more easy-to-use switch case statement. which can fulfill your requirement. We can use the find method in the switch statement to get the desire output.
switch(varname){
case["afshin","saeed","larry"].find(name => name === varname):
alert("Hey")
break;
default:
alert('Default case');
break;
}
The switch statement is used to select one of many code blocks to execute based on a condition
the value in the switch expression is compared to the different values provided
if there is a match the code block related to it will be executed
if there is no match the default block is executed
syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
NOTE:
It must be noted that if the break statement is omitted then the next block will be executed as well even if they does not match with switch expression. So don't forget to add the break statement at the end of each code block if you don't want to get the specified behaviour
A practical example:
the following code returns the current day of the week in strings based on an integer (provided by 'new Date().getDay()')
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
the code samples were taken from W3Schools
Another way of doing multiple cases in a switch statement, when inside a function:
function name(varName){
switch (varName) {
case 'afshin':
case 'saeed':
case 'larry':
return 'Hey';
default:
return 'Default case';
}
}
console.log(name('afshin')); // Hey
Cleaner way to handle that
if (["triangle", "circle", "rectangle"].indexOf(base.type) > -1)
{
//Do something
}else if (["areaMap", "irregular", "oval"].indexOf(base.type) > -1)
{
//Do another thing
}
You can do that for multiple values with the same result
Just change the switch condition approach:
switch (true) {
case (function(){ return true; })():
alert('true');
break;
case (function(){ return false; })():
alert('false');
break;
default:
alert('default');
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example1</title>
<link rel="stylesheet" href="css/style.css" >
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
function display_case(){
var num = document.getElementById('number').value;
switch(num){
case (num = "1"):
document.getElementById("result").innerHTML = "You select day Sunday";
break;
case (num = "2"):
document.getElementById("result").innerHTML = "You select day Monday";
break;
case (num = "3"):
document.getElementById("result").innerHTML = "You select day Tuesday";
break;
case (num = "4"):
document.getElementById("result").innerHTML = "You select day Wednesday";
break;
case (num = "5"):
document.getElementById("result").innerHTML = "You select day Thusday";
break;
case (num = "6"):
document.getElementById("result").innerHTML = "You select day Friday";
break;
case (num = "7"):
document.getElementById("result").innerHTML = "You select day Saturday";
break;
default:
document.getElementById("result").innerHTML = "You select day Invalid Weekday";
break
}
}
</script>
</head>
<body>
<center>
<div id="error"></div>
<center>
<h2> Switch Case Example </h2>
<p>Enter a Number Between 1 to 7</p>
<input type="text" id="number" />
<button onclick="display_case();">Check</button><br />
<div id="result"><b></b></div>
</center>
</center>
</body>
You could write it like this:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
For me this is the simplest way:
switch (["afshin","saeed","larry"].includes(varName) ? 1 : 2) {
case 1:
alert('Hey');
break;
default:
alert('Default case');
break;
}

jquery Using ranges in switch cases?

Switch cases are usually like
Monday:
Tuesday:
Wednesday:
etc.
I would like to use ranges.
from 1-12:
from 13-19:
from 20-21:
from 22-30:
Is it possible? I'm using javascript/jquery by the way.
you could try abusing the switch fall through behaviour
var x = 5;
switch (x) {
case 1: case 2: case 3: case 4: ...
break;
case 13: case 14: case 15: ...
break;
...
}
which is very verbose
or you could try this
function checkRange(x, n, m) {
if (x >= n && x <= m) { return x; }
else { return !x; }
}
var x = 5;
switch (x) {
case checkRange(x, 1, 12):
//do something
break;
case checkRange(x, 13, 19):
...
}
this gets you the behaviour you would like. The reason i return !x in the else of checkRange is to prevent the problem of when you pass undefined into the switch statement. if your function returns undefined (as jdk's example does) and you pass undefined into the switch, then the first case will be executed. !x is guaranteed to not equal x under any test of equality, which is how the switch statement chooses which case to execute.
Late to the party, but upon searching for an answer to the same question, I came across this thread. Currently I actually use a switch, but a different way. For example:
switch(true) {
case (x >= 1 && x <= 12):
//do some stuff
break;
case (x >= 13 && x <= 19):
//do some other stuff
break;
default:
//do default stuff
break;
}
I find this a lot easier to read than a bunch of IF statements.
You can make interesting kludges. For example, to test a number against a range using a JavaScript switch, a custom function can be written. Basically have the function test a give n value and return it if it's in range. Otherwise returned undefined or some other dummy value.
<script>
// Custom Checking Function..
function inRangeInclusive(start, end, value) {
if (value <= end && value >= start)
return value; // return given value
return undefined;
}
// CODE TO TEST FUNCTION
var num = 3;
switch(num) {
case undefined:
//do something with this 'special' value returned by the inRangeInclusive(..) fn
break;
case inRangeInclusive(1, 10, num):
alert('in range');
break;
default:
alert('not in range');
break;
}
</script>
This works in Google Chrome. I didn't test other browsers.
Nope, you need to use an if/else if series to do this. JavaScript isn't this fancy. (Not many languages are.)

Categories