javascript: switch statement - javascript

I'm trying to learn how to do a switch statement using javascript. Can you guys help me how to convert this one into switch statement?
if (x == ix && y == iy){//should be the default
x.style.backgroundColor = 'white';
}
if(x < ix){
x.style.backgroundColor = 'red';
}
else if(x > ix){
x.style.backgroundColor = 'blue';
}
if(y < iy){
x.style.backgroundColor = 'green';
}
else if(y > iy){
x.style.backgroundColor = 'yellow';
}

JavaScript does not support operations other than strict equality in switches. In other words, you cannot write that program as a switch.
In a switch, you can compare a variable to different values (or cases) and check if they are equal. If they are, you execute the code given under the case.
There is a drawback, however, and it is that you can convert this code into a switch easily:
if (a === 1) {
console.log("one");
} else if (a === 2) {
console.log("two");
} else {
console.log("Out of range! :(");
}
The above code in switch is
switch (a) {
case 1:
console.log("one");
break;
case 2:
console.log("two");
break;
default:
console.log("Out of range! :(");
break;
}
But you cannot do the same to a code that contains relational operations.
switch (a) {
case > 1: // throws error
doSomething();
break;
}

Hope this could be helpful to convert your above conditions.
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";
}

Related

Why this switch isn't giving any output? [duplicate]

Am I writing the correct switch case with conditions?
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
alert('31');
break;
default:
alert('>41');
}
For some reason, the alert does not occur when the conditions are matched!
A switch works by comparing what is in switch() to every case.
switch (cnt) {
case 1: ....
case 2: ....
case 3: ....
}
works like:
if (cnt === 1) ...
if (cnt === 2) ...
if (cnt === 3) ...
Therefore, you can't have any logic in the case statements.
switch (cnt) {
case (cnt >= 10 && cnt <= 20): ...
}
works like
if (cnt === (cnt >= 10 && cnt <= 20)) ...
and that's just nonsense. :)
Use if () { } else if () { } else { } instead.
You should not use switch for this scenario. This is the proper approach:
var cnt = $("#div1 p").length;
alert(cnt);
if (cnt >= 10 && cnt <= 20)
{
alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
alert('31');
}
else
{
alert('>41');
}
This should work with this :
var cnt = $("#div1 p").length;
switch (true) {
case (cnt >= 10 && cnt <= 20):
alert('10');
break;
case (cnt >= 21 && cnt <= 30):
alert('21');
break;
case (cnt >= 31 && cnt <= 40):
break;
default:
alert('>41');
}
Something I came upon while trying to work a spinner was to allow for flexibility within the script without the use of a ton of if statements.
Since this is a simpler solution than iterating through an array to check for a single instance of a class present it keeps the script cleaner. Any suggestions for cleaning the code further are welcome.
$('.next').click(function(){
var imageToSlide = $('#imageSprite'); // Get id of image
switch(true) {
case (imageToSlide.hasClass('pos1')):
imageToSlide.removeClass('pos1').addClass('pos2');
break;
case (imageToSlide.hasClass('pos2')):
imageToSlide.removeClass('pos2').addClass('pos3');
break;
case (imageToSlide.hasClass('pos3')):
imageToSlide.removeClass('pos3').addClass('pos4');
break;
case (imageToSlide.hasClass('pos4')):
imageToSlide.removeClass('pos4').addClass('pos1');
}
}); `
What you are doing is to look for (0) or (1) results.
(cnt >= 10 && cnt <= 20) returns either true or false.
--edit--
you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length.
--edit--
function date_conversion(start_date){
var formattedDate = new Date(start_date);
var d = formattedDate.getDate();
var m = formattedDate.getMonth();
var month;
m += 1; // JavaScript months are 0-11
switch (m) {
case 1: {
month="Jan";
break;
}
case 2: {
month="Feb";
break;
}
case 3: {
month="Mar";
break;
}
case 4: {
month="Apr";
break;
}
case 5: {
month="May";
break;
}
case 6: {
month="Jun";
break;
}
case 7: {
month="Jul";
break;
}
case 8: {
month="Aug";
break;
}
case 9: {
month="Sep";
break;
}
case 10: {
month="Oct";
break;
}
case 11: {
month="Nov";
break;
}
case 12: {
month="Dec";
break;
}
}
var y = formattedDate.getFullYear();
var now_date=d + "-" + month + "-" + y;
return now_date;
}
Switch case is every help full instead of if else statement :
switch ($("[id*=btnSave]").val()) {
case 'Search':
saveFlight();
break;
case 'Update':
break;
case 'Delete':
break;
default:
break;
}
Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.
What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.
Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.
Like follow:
switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
alert('10');
break;
case (cnt >= 21 && cnt <= 30 && cnt):
alert('21');
break;
case (cnt >= 31 && cnt <= 40 && cnt):
alert('31');
break;
default:
alert('>41');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>

how to use switch statment

im new with JS and i read about the switch statement. i dont know how to use it
i got an exercise to complete.
got an array with numbers 1-10 and the result need to be with words like "one","two","three"..
Thats what i got so far :
function sayNum(){
let nameNumber = [1,2,3,4,5,6,7,8,9,10]
let text = '';
for(let i=0;i<nameNumber.length;i++){
switch(numbers) {
case "1":
text = "one";
break;
case "2":
text = "two";
break;
case "3":
text = "three";
break;
case "4":
text='four';
break;
case "5":
text = "five";
break;
case "6":
text = "six";
break;
case "7":
text = "seven";
break;
case "8":
text = "eight";
break;
case "9":
text = "nine";
break;
case "10":
text = "ten";
}
}
return text;
}
sayNum()
You could do it like this, for example:
function sayNum(){
let numbers = [1,2,3,4,5,6,7,8,9,10];
let result = [];
for(let i=0;i<numbers.length;i++) {
switch(numbers[i]) {
case 1:
text = "one";
break;
case 2:
text = "two";
break;
case 3:
text = "three";
break;
case 4:
text = "four";
break;
case 5:
text = "five";
break;
case 6:
text = "six";
break;
case 7:
text = "seven";
break;
case 8:
text = "eight";
break;
case 9:
text = "nine";
break;
case 10:
text = "ten";
break;
}
result.push(text);
}
return result;
}
let namedNumbers = sayNum();
console.info(namedNumbers);
This will:
Add the textual values to an array, representing each number in the source array
Return the resulting array to the caller
Log the result in the console
In the switch statement, you pass an 'expression' into the switch statement. The expression itself can be a string, a number, float, boolean etc. Now, the expression is compared to each of the case clause. And this is a 'strict' comparison. And that is the reason why your code was not working.
Firstly you were passing an undeclared variable, 'numbers' as the switch expression. Instead, you should be passing the ith element of the nameNumber[i] array like so: switch(nameNumber[i]){ }
And, secondly, in each of your case clauses, you are comparing the value to a string like "1", "2". But the switch expression is compared using strict equality === operator, therefore when your nameNumber array contains numbers and not strings, your 'case' clauses should also have numbers and not strings. That means case 1: instead of case "1":.
You can read more about the switch-case here: Switch Statement
I have fixed your code below with the changes I mentioned above. Please run the below code snippet to see how it works. Goodluck!
function sayNum(){
let nameNumber = [1,2,3,4,5,6,7,8,9,10]
let text = '';
for(let i=0;i<nameNumber.length;i++){
switch(nameNumber[i]) {
case 1:
text = "one";
break;
case 2:
text = "two";
break;
case 3:
text = "three";
break;
case 4:
text='four';
break;
case 5:
text = "five";
break;
case 6:
text = "six";
break;
case 7:
text = "seven";
break;
case 8:
text = "eight";
break;
case 9:
text = "nine";
break;
case 10:
text = "ten";
}
console.log(text);
}
return text;
}
sayNum();
Rather than using a switch, use if statement. Because in switch, break statement can be used to jump out of a loop.
let text = '';
function sayNum() {
let nameNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < nameNumber.length; i++) {
if(nameNumber[i] == 1){
text += `"one",`;
}
if(nameNumber[i] == 2){
text += `"two",`;
}
if(nameNumber[i] == 3){
text += `"three",`;
}
if(nameNumber[i] == 4){
text += `"four",`;
}
if(nameNumber[i] == 5){
text += `"five",`;
}
if(nameNumber[i] == 6){
text += `"six",`;
}
if(nameNumber[i] == 7){
text += `"seven",`;
}
if(nameNumber[i] == 8){
text += `"eight",`;
}
if(nameNumber[i] == 9){
text += `"nine",`;
}
if(nameNumber[i] == 10){
text += `"ten"`;
}
}
}
sayNum();
console.log(text)

How do i make switch and if statement in one function

function texas(val) {
var answer = "";
switch(val) {
case 1:
case 2:
case 3:
var answer = "low";
case 4:
case 5:
case 6:
var answer = "medium";
break;
} else if(val => 7) {
var answer = "Huge"
}
return answer;
}
it says error Declaration or statement expected. ts(1128) [13, 7]
and it poits at the else if statement
You can use the "default" keyword, but you should probably update your code in order to handle the cases in which the value of the parameter is not positive or not a number:
function texas(val) {
if (val <= 0 || isNan(val)) {
throw new InvalidOperationException("val should be a positive number");
}
switch(val) {
case 1:
case 2:
case 3:
return "low";
case 4:
case 5:
case 6:
return "medium";
default:
return "Huge"
}
}
It's >= and the elsehas to be deleted. The varfor answer is unnecesary, just declare it once with let. You forgot the break in case 3:.
function texas(val) {
let answer = "";
switch(val) {
case 1:
case 2:
case 3:
answer = "low";
break;
case 4:
case 5:
case 6:
answer = "medium";
break;
}
if(val >= 7) {
answer = "Huge"
}
return answer;
}
console.log(texas(2));
console.log(texas(8));
You just need to return in the switch
function texas(val) {
var answer = "";
switch(val) {
case 1:
case 2:
case 3:
var answer = "low";
return answer;
case 4:
case 5:
case 6:
var answer = "medium";
return answer;
}
if(val => 7) {
var answer = "Huge"
}
return answer;
}
The syntax does not allow to put an else after a switch. else only makes sense in combination with an if statemen. But switch has a default: case which most closely matches your intention (hopefully):
function texas(val) {
var answer = "";
switch(val) {
case 1:
case 2:
case 3:
var answer = "low";
break;
case 4:
case 5:
case 6:
answer = "medium";
break;
default:
if(val >= 7) {
answer = "Huge"
}
// decide what should happen if val is 0, -1 or not even a number (e.g. texas('gotcha!')
break;
}
return answer;
}
Don't forget to put break in your cases, otherwise execution will "fall through" and execute the next cases. You would never end up with "low"
You can't use an if statement within a switch block.
You do have the default option tho -
function texas(val) {
var answer = "";
switch(val) {
case 1:
case 2:
case 3:
answer = "low";
case 4:
case 5:
case 6:
answer = "medium";
break;
default:
answer = val >= 7 ? "Huge" : "Invalid";
break;
}
return answer;
Note that if you have a minus / negative answer, it'll also fall into this clause, but you can the the value of answer with an inline ?: if statement...
You can't put the else after the switch block as people have stated above. switch statement is better for multi way branching and fixed data values. On the other side, if statement is better for boolean values. You can do something like this. It might not be the shortest line of codes, but just so you that there's another approach:
function texas(val) {
let answer = "";
switch (true) {
case (val == 1 || val == 2 || val == 3):
answer = "low";
break;
case (val == 4 || val == 5 || val == 6):
answer = "medium";
break;
case (val >= 7):
answer = "huge";
break;
}
return answer;
}

Javascript operators in switch case

I'm creating a panel and there are stats for memory, CPU and HDD. I'm using a switch statement and in the case method, I'm putting the current usage of CPU, memory and HDD.
However, the problem is that I'm using operators and I don't know which operator to use because I've tried all of them and I didn't get the results that I expected.
And this is the code: https://pastebin.com/YaxCm0Be
switch(true){
case (mem_percent_get <= 0.01):
var mem_progress_color = 'progress-bar-primary';
break;
case (mem_percent_get <= 33):
var mem_progress_color = 'progress-bar-success';
break;
case (mem_percent_get <= 66):
var mem_progress_color = 'progress-bar-warning';
break;
case (mem_percent_get <= 80):
var mem_progress_color = 'progress-bar-danger';
break;
default:
mem_progress_color = 'progress-bar-theme';
}
switch(true){
case (cpu_percent_get <= 33):
var cpu_progress_color = 'progress-bar-success';
break;
case (cpu_percent_get <= 66):
var cpu_progress_color = 'progress-bar-warning';
break;
case (cpu_percent_get <= 80):
var cpu_progress_color = 'progress-bar-danger';
break;
default:
cpu_progress_color = 'progress-bar-primary';
}
switch(true){
case hdd_percent_get <= 0.01:
var hdd_progress_color = 'progress-bar-primary';
break;
case hdd_percent_get <= 30:
var hdd_progress_color = 'progress-bar-success';
break;
case hdd_percent_get <= 60:
var hdd_progress_color = 'progress-bar-warning';
break;
case hdd_percent_get <= 80:
var hdd_progress_color = 'progress-bar-danger';
break;
default:
hdd_progress_color = 'progress-bar-theme';
}
Well, my first comment is to not use a switch in this case. What you are doing is essentially if () { } else if() {} blocks. You should be using switch when you have a value that you want to strictly check against. I suggest looking into at the MDN docs for switch.
Secondly, from what I can gather is that for the memory, you need it to be red when the value is 1696 / 2098 (80.83%). All of your if/elseif cases rely on <= which would mean that the value must be less than or equal to the number on the right of the equation. In your case, you are looking for <= 80, and without seeing how you calculate mem_percent_get (if it is in the pastebin, I'm unable to open that on my current network), you're value is likely above 80.
For your danger, you likely want 80-100+% as being red, so you should be using >= or greater than or equal to operator.
MDN has an excellent resources on comparison operators.
Created a getClassName method that accepts a percent and will return a className:
const getClassName = percent => {
switch(true){
case (percent <= 0.01):
return 'progress-bar-primary';
case (percent <= 33):
return 'progress-bar-success';
case (percent <= 66):
return 'progress-bar-warning';
case (percent <= 80):
return 'progress-bar-danger';
default:
return 'progress-bar-theme';
}
}
console.log('0: ', getClassName(0));
console.log('40: ', getClassName(40));
console.log('50: ', getClassName(50));
console.log('80: ', getClassName(80));
console.log('100: ', getClassName(100));

Javascript case statement in the switch Statement

I have a problem with the 'case' statement in the 'switch' statement in java script.
My question is how to write more than one number in the 'case' statement and save all the work on writing multiple of commands for each number , ill try to explain myself better. i want to write in the case statement the
number 10-14 (10,11,12,13,14).
how can i write it?
thanks for helping and sorry for my bad english.
name = prompt("What's your name?")
switch (name)
{
case "Ori":
document.write("<h1>" + "Hello there Ori" + "<br>")
break;
case "Daniel":
document.write("<h1>" + "Hi, Daniel." + "<br>")
break;
case "Noa":
document.write("<h1>" + "Noa!" + "<br>")
break;
case "Tal":
document.write("<h1>" + "Hey, Tal!" + "<br>")
break;
default:
document.write("<h1>" + name + "<br>")
}
age = prompt ("What's your age?")
switch (age)
{
case "10":
document.write("you are too little" + name)
break;
case "14":
document.write("So , you are in junior high school" + name)
break;
case "18":
document.write("You are a grown man" + name)
break;
default:
document.write("That's cool" + name)
break;
}
Check out this answer Switch on ranges of integers in JavaScript
In summary you can do this
var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x > 4 && x < 9):
alert("between 5 and 8");
break;
case (x > 8 && x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
but that sort of defeats the purpose of a switch statement, because you could just chain if-else statments. Or you can do this:
switch(this.dealer) {
case 1:
case 2:
case 3:
case 4:
// Do something.
break;
case 5:
case 6:
case 7:
case 8:
// Do something.
break;
default:
break;
}
use this, if you dont provide break then control will fall down, In this way you can match for group of numbers in switch.
case 10:
case 11:
case 12:
case 14:
case 15: document.write("i am less than or equal to 15");break;
Say you wanted to switch on a number 10-14 (10,11,12,13,14) you can chain the cases together:
switch(number) {
case 10:
case 11:
case 12:
case 13:
case 14:
alert("I'm between 10 and 14");
break;
default:
alert("I'm not between 10 and 14");
break;
}
You can simply omit the break; statement.
switch (2) {
case 1: case 2: case 3:
console.log('1 or 2 or 3');
break;
default:
console.log('others');
break;
}
I wanted to play with the concept a bit, I do not recommend this approach, however you could also rely on a function that will create a control flow function for you. This simply allows some syntaxic sugar.
var createCaseFlow = (function () {
var rangeRx = /^(\d)-(\d)$/;
function buildCases(item) {
var match = item.match(rangeRx),
n1, n2, cases;
if (match) {
n1 = parseInt(match[1], 10);
n2 = parseInt(match[2], 10);
cases = [];
for (; n1 <= n2; n1++) {
cases.push("case '" + n1 + "':");
}
return cases.join('');
}
return "case '" + item + "':";
}
return function (cases, defaultFn) {
var fnStrings = ['switch (value.toString()) { '],
k;
for (k in cases) {
if (cases.hasOwnProperty(k)) {
fnStrings.push(k.split(',').map(buildCases).join('') + "return this[0]['" + k + "'](); break;");
}
}
defaultFn && fnStrings.push('default: return this[1](); break;');
return new Function('value', fnStrings.join('') + '}').bind(arguments);
};
})();
var executeFlow = createCaseFlow({
'2-9': function () {
return '2 to 9';
},
'10,21,24': function () {
return '10,21,24';
}
},
function () {
return 'default case';
}
);
console.log(executeFlow(5)); //2 to 9
console.log(executeFlow(10)); //10,21,24
console.log(executeFlow(13)); //default case
You have already gotten a few answers on how to make this work. However, I want to point out a few more things. First off, personally, I wouldn't use a switch/case statement for this as there are so many similar cases – a classic if/elseif/else chain feels more appropriate here.
Depending on the use-case you could also extract a function and then use your switch/case (with more meaningful names and values, of course):
function getCategory (number) {
if(number > 20) {
return 3;
}
if(number > 15) {
return 2;
}
if(number > 8) {
return 1;
}
return 0;
}
switch( getCategory( someNumber ) ) {
case 0:
// someNumber is less than or equal to 8
break;
case 1:
// someNumber is any of 9, 10, 11, 12, 13, 14, 15
break;
// ...
}
If the intervals are equally spaced, you could also do something like this:
switch( Math.floor( someNumber / 5 ) ) {
case 0:
// someNumber is any one of 0, 1, 2, 3, 4
break;
case 1:
// someNumber is any one of 5, 6, 7, 8, 9
break;
// ...
}
Also, it should be noted that some people consider switch/case statements with fall-throughs (= leaving out the break; statement for come cases) bad practice, though others feel it's perfectly fine.

Categories