+ 3

Whats wrong with this JS code?

Like i can run it offline without internet successfully, but once i run it with the internet, it brings an error. alert("This checks if you passed a test"); //first i created a Array with the grades. var grades = ["failed", "credit", "merit", "distinction"] //next i created a funtion function testResult(score){ if (score <= "39") { return grades[0] } else if (score <= "59"){ return grades[1] } else if (score <= "79"){ return grades[2] } else if (score >= "80"){ return grades[3] } } //This where i call it console.log(testResult("90"))

26th Feb 2020, 5:49 AM
David Holmes Ng'andu
David Holmes Ng'andu - avatar
7 Respostas
+ 4
You can't compare quotes with numbers. In all if statements and in the last line remove the quotes.
26th Feb 2020, 6:04 AM
coddy
coddy - avatar
+ 4
The code runs fine from what I can see 90 is distinction and as I changed the value in the console.log line so it changed the array position https://code.sololearn.com/WGi18LIn6VFH/?ref=app
26th Feb 2020, 6:12 AM
BroFar
BroFar - avatar
+ 3
"90", "39", these are string. console.log(typeof "90"); console.log(typeof 90); Use number instead for comparison https://code.sololearn.com/WYiLQ2ulToL7/?ref=app
26th Feb 2020, 6:14 AM
Gordon
Gordon - avatar
+ 3
Further explanation it seems to work when comparing string, Because string are compared lexicographically. Take for examples, "b" > "a" https://code.sololearn.com/Wl0WNT3EJa2b/?ref=app but because "1" < "9" so "100" < "99" so we should still use number for numbers.
26th Feb 2020, 9:25 AM
Gordon
Gordon - avatar
+ 1
What kind of error is it? What does it tell you?
26th Feb 2020, 5:58 AM
Aiki
Aiki - avatar
+ 1
You should use integer in Your condición instead of string and have a range like else if (score >=40 && score <= 59)
27th Feb 2020, 2:30 AM
José Manuel Doñe Guillén
José Manuel Doñe Guillén - avatar
0
problem in strings. 1 !=== “1”
28th Feb 2020, 5:16 AM
Oleg
Oleg - avatar