HELP! My code isnt working and I dont know why!

Hi evryone, I am new to coding and am just trying some simple things and getting very frustrated because the outcome is not working. This is the code I made:

var car = ‘10’;
var train = ‘5’;

if (car > train)
{print (“Take the train”);}

else;
{print ("Buy a car");}

The Output is: Buy a car

I’m not understanding why that is the output when the value of car IS greater than the value of train Shouldn’t it be “Take the train”??? Any help would be greatly appreciated!!

1 Like

Hey Nicole! From what I can see, there is a semi-column after the else statement. This is because we don’t give ; in any condition of if else statements. Hope I corrected your code.

Hi Inthiyaz! Thank you so much for replying. Ok so I removed the semicolon but still getting the same result “Buy a car”. Have you tried it? Does it give you the same result that I get?

Hey! I see that the numbers 10 and 5 have been taken as strings. So just remove those apostrophes from both. Sorry I didn’t observe that earlier.

Ahhhhh yes! You’re right. Thank you! But question…why does it even return anything at all? With the code that I had, what is it recognizing the variable to be then?

Ariana I had the variables as strings instead of numbers! (Doh!) lol

Hey there, take a look at my reply to another user who had a similar issue here. That might help clear things up.

If you have any other questions, feel free to ask away!
Ben

Aah! Nice question. Now since we declared numbers as strings, we now cannot compare the lengths of strings with ‘>’ sign. Hence, since we are comparing them in the if statement, it doesn’t execute it. Rather,it moves to else block (as we aren’t comparing anything here) and it executes it.
It’s normal not being able to debug( lol that’s what got me in the first place) . Cheers;)

1 Like

@Nichole_Smith
@Inthiyaz_Ahmad_Khan

Hey there, you’re very close! It actually is comparing the strings, though it’s not checking their length.

When you use > or < with strings, it compares their “lexicographical order”, meaning the order they would appear in a dictionary. For example, 'bird' would appear before 'cat' in a dictionary, so 'bird' < 'cat' === true.

The string '10' would appear before the string '5', so '10' < '5' === true, even though the number 10 is greater than the number 5.

Hope that makes sense. Let me know if you have any questions.
Ben

2 Likes