Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
}
like image 944
troubledcoder Avatar asked Apr 13 '26 11:04

troubledcoder


1 Answers

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');
}
like image 101
BladeOfLightX Avatar answered Apr 14 '26 23:04

BladeOfLightX