Shortband for switch..case doesn't work - javascript

I am clueless why this piece of code doesn't work:
switch (Category.getValue()) {
case 1: () => { for (var i = 0; i < 12; i++) OptionSet.addOption(options[i]); }; break;
default: () => { OptionSet.clearOptions(); }; break;
}
It hits case 1:, but then instead of doing loop it just quits switch statement.

With your code () => {} You are essentially defining an anonymous function without assigning or calling it. You can remove that part from the code and it will work. Example

Related

How to get Functions output and re-use within IF/else Statement

I have function at the bottom of my script which counts for how many tools were used.
Then based on how many tools were used I want to perform different actions.
I can easily check the output of the Function but I struggle to put it into If statement.
How to get Functions output and re-use it within IF Statement?
var HowManyTools = HowManyTools1();
if (HowManyTools <= 2) {
Category13();
} else if (HowManyTools >= 6) {
Category14();
} else if (HowManyTools > 2) {
Category12();
}
function HowManyTools1() {
//returns value between 1-9
}
Update: I've added if to the last else. It executes the Category13();. Without if all previous statements were simply false so it went straight to the last statement with Category12();
I can output into Category13/ Category12. But not the Category14.
It seems like my function can't get defined, as soon as I put it within a variable, and if I try to alert(HowManyTools) I simply get undefined Error.
Tried a few examples from here but to no avail
This variant should demonstrate that every one of your Category functions will run if its if-condition is met.
I pass HowManyTools to each of those functions for demonstration purposes.
for (var i = 0; i < 20; i++) {
test();
}
function test () {
var HowManyTools = HowManyTools1();
if (HowManyTools <= 2) {
Category13(HowManyTools);
} else if (HowManyTools >= 6) {
Category14(HowManyTools);
} else if (HowManyTools > 2) {
Category12(HowManyTools);
}
}
function HowManyTools1() {
return Math.floor(Math.random() * 9 + 1);
}
function Category12(val) {
console.log(`Category 12: value = ${val}`);
}
function Category13(val) {
console.log(`Category 13: value = ${val}`);
}
function Category14(val) {
console.log(`Category 14: value = ${val}`);
}

Switch Statement and jQuery hasClass function

I am trying to use a switch statement to check if the current page has a specific body class. This is kind of what I am looking for:
var bodyClass = $('body').hasClass('className')
switch(bodyClass) {
case 'homepage':
// console.log("This is the homepage");
break;
case 'residential-page':
// console.log("This is the residential page");
break;
default:
// console.log("default code block ran");
}
I do understand that the jQuery hasClass function returns true of false and is used like $('body').hasClass('someClassName') and this will return true or false. Also, my body typically has about 7-10 different class names for a given page.
This is not the use case for a switch in my opinion, but a simple set of branches
var body = $('body');
if(body.hasClass('abc')) {
}
else if(body.hasClass('def')) {
}
else {
/* default case */
}
/* etc */
I agree with the other answer that you're better suited to just use if, else if statements here, but an alternative would be to rip the classes off the body tag and check them against your strings:
var bodyClasses = ($('body').attr('class') || '').split(' ');
for (var i = 0, len = bodyClasses.length; i < len; i++) {
switch(bodyClasses[i]) {
case 'homepage':
// console.log("This is the homepage");
break;
case 'residential-page':
// console.log("This is the residential page");
break;
default:
// console.log("default code block ran");
}
}
I know this is an old thread, but it may help someone else.
If you are able to ensure the classes for the element are declared in a specific order, you could ensure the class you are checking for is first / last in the list, and use something similar to this:
var bodyClass = $('body').attr('class');
var firstClass = bodyClass.slice(0, bodyClass.indexOf(' '));
switch(firstClass) {
case 'homepage':
// Some code here
break;
case 'residential-page':
// Other code here
break;
default:
// More code here
}

Javascript - evaluating parameter again

I would like to create a function "when", that will work as a normal command, or just a function, and will be able to re-evaluate its parameters.
for example:
when(k==0) {
do something;
}
or
when(k==0, function() {
do something;
});
The thing is, that k is now for example equal to 1, and this function needs to always re-evaluate k==0 to determinate if it changed to 0.
*I do not want to send k==0 as a string 'k==0'.
Is that possible? If so, how?
*This is an academic question, please don't explain why it is so very wrong to create this function.
something like this?
function when(condition, callback){ if (condition) callback() }
and call it like
var a = 0;
when(a == 0, function(){ console.log( "yeyyyy") } );
after reading the comments above
some kind of mechanism for observing when a variable's value changes
change when method to
function when(lhs, operator, rhs, callback)
{
var result = false;
switch( operator )
{
case "==": result = (lhs==rhs); break;
case "===": result = (lhs===rhs); break;
case "<": result = (lhs<rhs); break;
case ">": result = (lhs>rhs); break;
case "<=": result = (lhs<=rhs); break;
case ">=": result = (lhs>=rhs); break;
default: result = true;
}
if (result) { callback() }
else { setTimeout( function(){ when(lhs, operator, rhs, callback) }, 1000 ); }
}
What would work would be to use a lambda for both the condition and the action. Using arrow function expressions (thanks #Kyll), it's even reasonably compact.
when (() => k == 0, () => { do something; });

From IF/ELSE to Switch in Javascript

So, I'm trying to substitute the code within the IF statements to run the same way in a Switch statement. However, I can't seem to understand how to get the functions to run the same way in the switch as they do in the if statement. Here's the code I've written with the if statement. Could anyone help me figure out how to format it correctly to run with the switch statement instead?
function processInput() {
listitem = "item" + i;
document.getElementById(listitem).innerHTML = document.getElementById('toolBox').value;
document.getElementById('toolBox').value = '';
if (i == 5) {
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
}
i++;
}
I am not sure why you want the switch but for sample purposes here is how a switch would work for the code you posted above:
function processInput() {
listitem = "item" + i;
document.getElementById(listitem).innerHTML = document.getElementById('toolBox').value;
document.getElementById('toolBox').value = '';
switch(i) {
case 5:
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
break;
default:
// any code you want to run in the else statement
}
i++;
}
This switch statement would replace the current if statement that you have.
switch (i) {
case 5:
document.getElementById('resultsExpl').innerHTML = "Thanks for your suggestions";
}

javascript switch(true)

Hi i am trying to handle an ajax json response
here is my code
success: function (j) {
switch(true)
{
case (j.choice1):
alert("choice2");
break;
case (j.choice2):
alert("choice2");
break;
default:
alert("default");
break;
}
}
based on what j is return i do my action BUT i keep getting the default.
I have alert the j values and come correct.Some how case (j.choice1) case (j.choice2) is not working.
I tried case (j.choice1!="") (j.choice2!="") But in this scenario i keep getting the first choice.
What am i missing
It works for me:
var a = 0, b = true;
switch(true) {
case a:
console.log('a');
break;
case b:
console.log('b');
break;
}
However, the case labels must be equal to true, not just implicitly true.
Also, only the first case that evaluates to true will execute.
SOLVED
Based on SLaks answer i modify the code as below
if(j.choice1){ var choice1=true;} else { var choice1=false;}
if(j.choice2){ var choice2=true;} else { var choice2=false;}
switch(true)
{
case choice1:
alert("choice1");
break;
case choice2:
alert("choice2");
break;
default:
alert("default");
break;
}
For all asking why switch and not if.
Switch will execute only 1 statement, but if can execute more than 1 if any mistake come form response (for example if set choice1 and choice 2 the if will alert both but switch will alert only choice1).
The response expecting as choice has to do with credit card charge to bank so i want to ensure that only 1 action will exetute
Thank to all
You need to read up on the switch statement. You should not be switching on a constant value.
It appears that you need to use if statements, as you don't really want to be switching on your j value:
success: function (j) {
if (j.choice1)
{
alert("choice1");
break;
}
if (j.choice2)
{
alert("choice2");
break;
}
alert("default");
}
}
In a case like this, a better way to do this is probably something like:
success: function (j) {
if(j.choice1 || j.choice2) {
alert("choice2");
} else {
alert("default");
}
}
Why not use an object literal instead of a switch(true) ?
const j= {
choice1: false,
choice2: true
};
const map = {
true: 'default',
...(j.choice1 ? {[`${j.choice1}`]: 'choice1'} :{}),
...(j.choice2 ? {[`${j.choice2}`]: 'choice2'} :{})
}['true']
console.log(map) // 'choice2'

Categories

Resources