Why is my switch case not working in JavaScript? - javascript

I want the variable CurrectcoinValue will get the value of the correct case, but it's not working.
const CurrectcoinValue = "null";
const symbol = "usdt";
casim(symbol, CurrectcoinValue);
console.log("result : " + CurrectcoinValue);
function casim(symbol, CurrectcoinValue) {
switch (symbol) {
case "btc":
CurrectcoinValue = "BTC";
break;
case "eth":
CurrectcoinValue = "ETH";
break;
case "usdt":
CurrectcoinValue = "USDT";
break;
case "usdc":
CurrectcoinValue = "USDC";
break;
default:
CurrectcoinValue = 1;
}
}

There are 2 fundamental problems with your solution:
If you want to be able to change a variable, you need to declare it with let or var (preferably let because the scope is tighter). const is used when explicitly you don't want a variable to be changed.
You can't set a string variable from within a function, JS won't change that variable since it doesn't keep a reference to it!
Also, i think that we have a better way to treat this, which is using a function that does not change any parameter reference, only calculating the value:
const symbol = "usdt";
const CurrectcoinValue = casim(symbol);
console.log("result : " + result);
function casim(symbol) {
switch (symbol) {
case "btc":
return "BTC";
case "eth":
return "ETH";
case "usdt":
return "USDT";
case "usdc":
return "USDC";
default:
return 1;
}
}
This way you are not battling with reference issues.
You could also take the advice of using the symbol.toUpperCase(); method for the cases that are not the default, that would save some code repetition :)

Related

Changing style through JavaScript doesn't work with variables

I want to do is change the left margin of a DOM element based on a variable in JavaScript. This function works:
function updateTabs(i) {
console.log('Switching to tab ' + i)
switch(i) {
case 0:
document.querySelector('#About-content1').style.marginLeft = "0";
break;
case 1:
document.querySelector('#About-content1').style.marginLeft = "-100%";
break;
case 2:
document.querySelector('#About-content1').style.marginLeft = "-199%";
break;
default:
break;
}
}
This successfully sets the margin-left property like I want it to. However, I don't want to call document.querySelector every time I call the updateTabs function. I tried this:
var contentDiv1 = document.querySelector('#About-content1');
function updateTabs(i) {
console.log('Switching to tab ' + i)
switch(i) {
case 0:
contentDiv1.style.marginLeft = "0";
break;
case 1:
contentDiv1.style.marginLeft = "-100%";
break;
case 2:
contentDiv1.style.marginLeft = "-199%";
break;
default:
break;
}
}
However, this only works the first time I call the function. After that, it prints "Switching to tab" but doesn't actually modify the style. Is there any way I could change the style without having to call document.querySelector every time?
I think the reason is that the second time around it doesn't know what contentDiv1 is how about you put that inside the function like this:
function updateTabs(i) {
var contentDiv1 = document.querySelector('#About-content1');
console.log('Switching to tab ' + i)
switch(i) {
case 0:
contentDiv1.style.marginLeft = "0";
break;
case 1:
contentDiv1.style.marginLeft = "-100%";
break;
case 2:
contentDiv1.style.marginLeft = "-199%";
break;
default:
break;
}
}
So now everytime the function runs it knows what contentDiv1 is. So now you still call document.querySelector only once but the function know what you want.
The question is missing some context, but if Hadi Pawar's answer isn't correct, my guess is that the element is being destroyed and recreated. This should validate that:
var contentDiv1 = document.querySelector('#About-content1');
contentDiv1.myResize = function(i) {
console.log('Switching to tab ' + i)
var offsets = [0, -100, -199];
if( i > offsets.length ) return;
this.style.marginLeft = offsets[i] + '%';
}
[...]
contentDiv1.myResize( n );
Now, when you call resize, you will get a hard error if 'contentDiv1' loses scope. Otherwise, the logic is contained within the element itself.
Turns out that the problem was that I had a Vue.js element connected to the same element, so the element was changed. I moved the Vue.js declaration to before the const contentDiv1 = document.querySelector('#About-content1'), and it fixed the problem.

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

Cannot read property 'done' of undefined due to switch

I have a function which gaining data by ajax. The problem is that construction switch causing this error:
cannot read property 'done' of undefined
I don't know why...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
function changeSelect(input,type)
{
var out;
switch(type)
{
case "sport" : out=$.post("/ajax/ajax.php",{sport:input.value});
case "competition" :out=$.post("/ajax/ajax.php",{competition.value});
}
out.done(function(data)
{
$("#output").html(data);
});
}</script>
Thanks for answer.
The likely cause of the error you are getting is that the value of type does not match either of your case statements. Thus, out remains undefined and gives you the error you see.
In addition, you must use break; statements in case of your case: statements and {competition.value} is not valid ES5 Javascript. Perhaps you want something like this:
function changeSelect(input, type) {
var out;
switch (type) {
case "sport":
out = $.post("/ajax/ajax.php", {sport: input.value});
break;
case "competition":
out = $.post("/ajax/ajax.php", {sport: competition.value});
break;
default:
break;
}
if (out) {
out.done(function(data) {
$("#output").html(data);
});
}
}
I don't know exactly what you meant with your {competition.value}. I guessed that maybe you wanted it to be {sport: competition.value}, but I don't see competition defined anywhere so I'm not really sure.
Or, perhaps remove some duplicate code and use this:
function changeSelect(input, type) {
var val;
switch (type) {
case "sport":
val = input.value;
break;
case "competition":
val = competition.value;
break;
default:
break;
}
if (val) {
$.post("/ajax/ajax.php", {sport: val}).then(function(data) {
$("#output").html(data);
});
}
}

Javascript switch statement using regular expressions

I'm attempting an exercise and can't quite understand where I'm going wrong.
I have a form where my postcode field will only validate if it meets the requirements of the regex specific to the state chosen.
I need to use a switch statement to determine what RegEx to use based on the state choice.
This is what I have so far:
function validPostCode() {
var state = (document.getElementById("state").value);
switch (state) {
case "SA":
var stateRegEx = /^5([0-9]{3})$/;
break;
case "NSW":
var stateRegEx = /^2([0-9]{3})$/;
break;
}
return stateRegEx.test(document.getElementById("postcode").value);
}
Try this:
function validPostCode() {
var state = (document.getElementById("state").value);
var stateRegEx; // added here
switch (state) {
case "SA":
stateRegEx = /^5([0-9]{3})$/; // var removed
break;
case "NSW":
stateRegEx = /^2([0-9]{3})$/; // var removed
break;
}
return stateRegEx.test(document.getElementById("postcode").value);
}

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