Javascript weird bug?

ertaboy356b

Old School Gamer
Reaction score
86
I am recently writing a small javascript game for fun until I hit a roadblock.. At first, I had a hard time figuring out what is wrong with the code. Due to further testing, I concluded that the problem is this:

x = 3;
y = 5;
x + y = 8; // this is correct
x + "." + y = "3.5" // another correct answer
x + "." + y - 1 = "2.5" // WTF!

you can recreate it on Chrome's console. C'mon, try it :D

Typecasting and parenthesis fixed it though.
 

Artificial

Without Intelligence
Reaction score
326
The last one isn't actually the string [ljass]"2.5"[/ljass], but the number [ljass]2.5[/ljass], which makes it a bit more understandable. This result might seem a bit weird, but it's actually just a result of JavaScript's automatic type conversion and is quite well defined (though maybe not the best idea in the world).

In your example, when the interpreter comes across the expression [ljass]3 + "."[/ljass] it's like "Hey, I can't add a string to a number. But I can add two strings together, so I should just convert the number to a string!" So it goes on and executes the code [ljass]ToString(3) + "."[/ljass] (ToString) which results in the string [ljass]"3."[/ljass]

When you tell the interpreter to execute the code [ljass]"3.5" - 1[/ljass] it's like "Hey, I can't subtract a number from a string! Can I subtract a string from a string? Nope. So let's cast the string to a number, because I can subtract a number from a number." So it goes on and executes the code [ljass]ToNumber("3.5") - 1[/ljass] (ToNumber), which results in the number [ljass]2.5[/ljass].

This functionality is defined in the ES5 specification's sections 11.6.1 The Addition operator ( + ) and 11.6.2 The Subtraction Operator ( - ).
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top