Switch...case in JS - javascript

This simple problem gives me an error. Does not get the correct answer. I will be glad if you help.
let point = 90;
switch (point) {
case point >= 51 && point <= 60:
console.log('Your price: E');
break;
case point >= 61 && point <= 70:
console.log('Your price: D');
break;
case point >= 71 && point <= 80:
console.log('Your price: C');
break;
case point >= 81 && point <= 90:
console.log('Your price: B');
break;
case point >= 91 && point <= 100:
console.log('Your price: A');
break;
default:
console.log('You did not pass');
}
Output: You did not pass

this way
let point = 90;
switch (true) {
case point >= 51 && point <= 60:
console.log('Your price: E');
break;
case point >= 61 && point <= 70:
console.log('Your price: D');
break;
case point >= 71 && point <= 80:
console.log('Your price: C');
break;
case point >= 81 && point <= 90:
console.log('Your price: B');
break;
case point >= 91 && point <= 100:
console.log('Your price: A');
break;
default:
console.log('You did not pass');
}
can you explain why we write true? – Hussein Nadjafli (PO)
The JS switch only works on strict equality.
switch (A) {
case ‘x1’: ...
case ‘x2’: ...
is equivalent to
if (A === ’x1’) { ...
else if (A === ’x2’) { ...
in your code you replace the possible values [’x1’,’x2’,...] with an evaluation like
(point >= 61 && point <= 70)
which returns either true or false
so your code becomes:
if (A === (point >= 51 && point <= 60)) { ...
else if (A === (point >= 61 && point <= 70)) { ...
by replacing the A by true you therefore have a comparison between:
if (true === (point >= 51 && point <= 60)) { ...
else if (true === (point >= 61 && point <= 70)) { ...
You can also do:
function codePrice(val)
{
let code = 'ABCDE'[10 - Math.ceil(val / 10)]
return (!!code) ? `Your price: ${code}` :'You did not pass'
}
console.log( codePrice(90) )

Can also be simplified:
let point = 90;
switch (true) {
case point < 51:
console.log('You did not pass');
break;
case point < 61:
console.log('Your price: E');
break;
case point < 71:
console.log('Your price: D');
break;
case point < 81:
console.log('Your price: C');
break;
case point < 91:
console.log('Your price: B');
break;
default:
console.log('Your price: A');
break
}

Related

Any particular reason why this switch-case statement in js is returning undefined?

Here is my code. I have cross checked with online docs and couldn't find any reason for this to not work.
let marks = 90;
switch (marks) {
case 1:
if (marks <= 100 && marks >= 80) {
console.log("Very Good");
}
break;
case 2:
if (marks >= 60 && marks <= 79) {
console.log("Good");
}
break;
case 3:
if (marks >= 30 && marks <= 59) {
console.log("Can do better");
}
break;
case 4:
if (marks < 30) {
console.log("Fail");
}
break;
}
let marks = 90;
switch (marks<=100) {
case marks <= 100 && marks>=80:
console.log("Very Good");
break
case ( marks >=60 && marks <= 79) :
console.log("Good")
break;
case (marks >= 30 && marks <=59):
console.log("Can do better");
break;
case (marks < 30) :
console.log("Fail");
break;
}
This should work your switch cases don't make sense

Switch statement in JavaScript is not able to run my code Properly

var aged = 14;
switch (aged) {
case aged <= 13:
document.write("Child");
break;
case aged >= 14 && aged <= 18:
document.write("Teen");
break;
case aged >= 19 && aged <= 59:
document.write("Adult");
break;
default:
document.write("Boomer");
}
it just keeps outputting BOOMER!!
I honestly don't know what to do
I got the syntax right but I'm still confused
Because each of your case branches provide a boolean value, you need to match against a boolean.
Your logic is such that you want to enter a branch upon a true evaluation, so use true in the head of the switch.
var aged = 14;
switch (true){
case aged <= 13:
document.write("Child");
break;
case aged >= 14 && aged <= 18:
document.write( "Teen" );
break;
case aged >= 19 && aged <= 59:
document.write("Adult");
break;
default:
document.write("Boomer");
}
I think if/else would maybe be preferable here.
var aged = 14;
if (aged <= 13) {
document.write("Child");
} else if (aged >= 14 && aged <= 18) {
document.write( "Teen" );
} else if (aged >= 19 && aged <= 59) {
document.write("Adult");
} else {
document.write("Boomer");
}
You could also use the conditional operator, but I'd use it to provide a value instead of control the flow of the program.
var aged = 14;
var result = aged <= 13 ? "Child" :
aged >= 14 && aged <= 18 ? "Teen" :
aged >= 19 && aged <= 59 ? "Adult" :
"Boomer";
document.write(result);
And your conditions are a little redundant. You can simplify like this:
var aged = 14;
var result = aged <= 13 ? "Child" :
aged <= 18 ? "Teen" :
aged <= 59 ? "Adult" :
"Boomer";
document.write(result);

=> operator "undefined" error while trying to compare values in a switch statement

I'm taking an introductory course on Javascript at my college and in my assignment, I had to write a function that took a value passed into the parameter and compares it through a switch statement. This is what I did:
function grader(mark) {
switch (mark) {
case (mark >= 80 && mark <= 100) :
return 'A';
break;
case (mark >= 70 && mark <= 79) :
return 'B';
break;
case (mark >= 60 && mark <= 69) :
return 'C';
break;
case (mark >= 50 && mark <= 59) :
return 'D';
break;
case (mark >= 0 && mark <= 49) :
return 'F';
break;
}
}
But the error I'm getting on scratchpad is this:
Exception: SyntaxError: expected expression, got '>'
#Scratchpad/2:3
*/
/*
undefined
*/
What does it mean when an operand is undefined?
NO switch cases cannot check a value in the range.
switch (expression) {
case value1:
//Statements executed when the
//result of expression matches value1
[break;]
case value2:
//Statements executed when the
//result of expression matches value2
[break;]
That clearly tells that the case should be a specific value.
You should go with tradational if else if
if (mark >= 80 && mark <= 100){
return 'A';
}
else if (mark >= 70 && mark <= 79) {
return 'B';
}

Using Keypress and keydown for for firefox,chrome, and ie

Im using keydown and keypress, this code only working on chrome but not in firefox.
the 1st function is User can only use number, numpad, backspace and tab. Another function is, when user typing a number it will automatically change to decimal
default --> 0.00
enter 1 --> 0.01
enter 0 --> 0.10
enter 0 --> 1.00
You can find my demo
here
$('#txtInput').keydown(function(event) {
var Key = event.which;
//number
if (Key >= 48 && Key <= 57) {
return true;
}
//numpad
else if (Key >= 96 && Key <= 105) {
return true;
}
//backspace,tab
else if (Key >= 8 && Key <= 9) {
return true;
}
else return false;
});
$(document).ready(function(){
$('#txtInput').keypress(function(e){
var value = $('#txtInput').val().toString();
var number = null;
if(value == '')
value = '0.00';
switch(e.which)
{
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
number = e.which - 48;
break;
default:
e.preventDefault();
break;
}
var dotIndex = value.indexOf('.');
if(number === null)
{
value = value.substr(0,dotIndex-1) + '.' + value.substr(dotIndex -1,1) + value.substr(dotIndex+1,1);
if(value.indexOf('.') ==0)
{
value = '0' + value;
}
}
else
{
value = value.substr(0,dotIndex) + value.substr(dotIndex+1,1) + '.' + value.substr(dotIndex+2);
value += number.toString();
value = value.replace(/^0+/,'');
if(value.indexOf('.') == 0)
{
value = '0' + value;
}
}
$('#txtInput').val(value);
e.preventDefault();
}).keypress(function(e){
switch(e.which)
{
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
e.preventDefault();
break;
}
});
});

Using mathematics in a switch statement case? [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>

Categories

Resources