Reputation: 27
I have a function which appears to always be returning true on the first condition irrelevant of input. I have been reading about using switch versus else if as I have 16 conditions to check and I want to ensure I have working 'best practice'
Can I achieve the same thing using both options:
function lsaupdateTotals() {
var x = variablename.value;
var y = variablename2.value;
if (x = 1) || (y = y > 1 && y < 280) {
rdlsa = 7.45;
} else if (x = 2 || (y = y > 281 && y < 460)) {
rdlsa = 11.65;
/ or switch: /
switch (x) {
case 1:
case y > 1:
case y < 280:
y = 7.45;
break;
}
Upvotes: 0
Views: 59
Reputation: 1472
You've got a few issues in your code:
=
instead of ==
or ===
to check equality in your if
statements. A single =
sign always means "set equal to", not "is equal to?".if
statement your parens make things a bit ambiguous. It's possible that this works just fine, but wrapping the entire question in parens is guaranteed to work as intended while also being completely clear.Rewriting your if
statement according to the above:
if (x == 1 || (y == y > 1 && y < 280)) {
rdlsa = 7.45;
}
else if (x == 2 || (y == y > 281 && y < 460)) {
rdlsa = 11.65;
}
(EDIT: Note that the y == y > 1
part is almost definitely not doing what you want it to. That's asking "is y the same thing as y > 1?")
In your switch
, think of the value in each case
as being a place holder for what you're putting into it. So in your example, using y>1
doesn't make sense to evaluate against x
, because it's asking if x
is *equal to y>1
, but y>1
is always true
or false
and is independent of x
.
Upvotes: 2
Reputation: 1486
you are getting the conditions wrong. Please replace your code with the below lines
function lsaupdateTotals() {
var x = variablename.value;
var y = variablename2.value;
if ((x == 1) || (y > 1 && y < 280)) {
rdlsa = 7.45;
} else if ((x == 2) || (y > 281 && y < 460)) {
rdlsa = 11.65;
}
/ or switch: /
switch (x) {
case 1:
case y > 1:
case y < 280:
y = 7.45;
break;
}
Upvotes: 1
Reputation: 767
There are several problem in your code:
===
, so if (x = 1)
should became if (x === '1')
(as I'm expecting x
is a string).if
condition should be in a parenthesis: if (x = 1) || (y = y > 1 && y < 280) {
=> if ((x === 1) || (y === y > 1 && y < 280)) {
y = y > 1
(or y === y > 1
) in first if (second parenthesis)y>1
, please refer to switch/case syntax (internet is full of documentation)=
instead of ===
) the if
statement consider true
the condition if the value after the =
is not null
, 0
, empty string, false
or undefined
, for this reason when you write if(x=1){
the condition is always true
.Upvotes: 4