troubledcoder
troubledcoder

Reputation: 69

Javascript condition not accurate to me

I'm trying to get the bigger score to print, it works for numbers until 10, however for a reason unclear to me numbers above 10 do not work as expected, with for example firstScore being 10 and secondScore 5, yet it would print 5 instead of 10.

var firstScore = prompt('First exam score?');
var secondScore = prompt('Second exam score?');

if (firstScore > secondScore) {
  console.log(firstScore);
} else if (secondScore > firstScore) {
  console.log(secondScore);
} else {
  console.log('Wrong parameter');
}

Upvotes: 2

Views: 49

Answers (2)

Julien Maret
Julien Maret

Reputation: 41

The thing is you are trying to compare two strings, try parsing the result get from your prompt to integer or float with parseInt() like this :

var firstScore = parseInt(prompt('First exam score?'));
var secondScore = parseInt(prompt('Second exam score?'));

if (firstScore > secondScore) {
    console.log(firstScore);
} else if (secondScore > firstScore) {
    console.log(secondScore);
} else {
    console.log('Wrong parameter');
}

Upvotes: 4

BladeOfLightX
BladeOfLightX

Reputation: 534

As the comment says, the return type is string but according to you, you want that to be int to perform mathematical operations. Simple solution will be to parse the input to int

var firstScore = parseInt(prompt('First exam score?'))
var secondScore = parseInt(prompt('Second exam score?'))

if (firstScore > secondScore) {
    console.log(firstScore);
} else if (secondScore > firstScore) {
    console.log(secondScore);
} else {
    console.log('Wrong parameter');
}

Upvotes: 4

Related Questions