Reputation: 21
I have a basic table in javascript and a few lines of code where I compare the first values from each of the two tables. It skips the 'else if' statement and just goes straight to the 'else' at the end, when the 'else if' condition is true. I'm pretty new to all this so I won't be surprised if I messed up somewhere obvious. Any help is much appreciated.
var firstEquation = ['2', 'x', '+', '1', 'y', '=', '8'];
var secondEquation = ['3', 'x', '-', '1', 'y', '=', '7'];
if ( firstEquation[1] > secondEquation[1] ) {
print("Outcome 1");
} else if ( firstEquation[1] < secondEquation[1] ) {
print("Outcome 2");
} else {
print("Else");
}
Upvotes: 1
Views: 1783
Reputation: 2099
JavaScript starts counting array indexes at 0. You've essentially said:
if ( "x" > "x" ) {
print("Outcome 1");
} else if ( "x" < "x" ) {
print("Outcome 2");
} else {
print("Else");
}
Since "x"
is the second element in each array, and "x" = "x"
, you will always hit the else statement. Change your array indexes to firstEquation[0]
and secondEquation[0]
to compare the first elements of the arrays.
Upvotes: 2
Reputation: 26
You are comparing the second value, to compare first value use [0]. It goes straight to the last else because 'x' is not less nor greater than 'x'
Upvotes: 0
Reputation: 9427
Are you sure you want to use print
? That's for sending data to paper.
It's possible you mean console.log
- which would send that output to the console
. If you came from a language such as python, then it would make sense that you didn't realise.
Upvotes: 1