BLOG: Mitch Wilson, Austin TX Web & Multimedia Developer – Austin, TX

3Apr/100

What does "1" + 2 + 3 equal?

We're talking JavaScript here. Kind of a trick question. Given operator precedence, I thought that the addition would have been performed first. For example, if multiplication were involved, it would be done before string concatenation, even if at the end of the statement (see Example C). What does "1" + 2 + 3 equal? You might guess 15, but that would be incorrect. The answer is the string "123." Let's test it and learn about operator precedence involving JavaScript strings.

Example A

<script>
var a = '1' + 2 + 3; // equals "123"
document.write(a);
</script>

The code simply runs left to right. And "1" + 2 comes before 2 + 3. What matters is, reading left to right, the datatype mix of the pair of values associated by the + operator. The first pair is "1" + 2, so that is evaluated first. The result of "1" + 2 will then be added to 3.

So here is what happens.

  1. "1" + 2 runs first and equals "12" because the operand "1" is a string, JavaScript performs datatype conversion on the 2 to convert it to a string "2" and then the + operator does concatenation to produce "12."
  2. Now, in memory while the program is running, we have "12" + 3 to process next. Again, because one of the operands is a string, JavaScript converts the number 3 to a string and performs concatenation on "12" + "3" to produce the final result "123"

Example B

Another example. Addition occurs among pairs from left to right, eg, 1 + 1 being the first pair, until a string is encountered.

<script>
var b = 1 + 1 + '2' + 3; // equals "223"
document.write(b);
</script>

When a string is encountered, the JavaScript interpreter performs concatenation and converts any non-string arguments to a string. The result is 1 + 1 = 2, then 2 + '2' involves a string, so the number 2 is converted into the string '2' and we have '2' + '2' = '22'. Then the final '22' + 3 results in '22' + '3' = '223' and we're done.

Example C

The final example shows how crazy this can be. When concerning addition vs. concatenation, we move from left to right. When other operations are involved, we might start at the end then move left to right.

<script>
var c = 1 + 1 + '0' + 2 * 5; // equals "2010"
document.write(c);
</script>

Example C shows that the last pair, 2 * 5, because it involves multiplication, is evaluated first, after which we have 1 + 1 + '0' + 10. Then 2 + '0' + 10. Then '20' + 10 that finally equals '2010' and we're done.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • RSS
  • Twitter
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.