Skip to navigation

1 + 1 = 11

This post talks about Javascript and the unfortunate combination of two quirks which can cause a few surprises.

Quirk 1: + as addition and concatenation

Javascript, unlike other languages use the same symbol for number addition and string concatenation:

1 + 1 => 2
'1' + '1' => '11'

Quirk 2: implicit type conversion

Javascript does not always throw an error when evaluating expressions with an odd mix of values and operators, such as, ‘10′ / ‘5′, instead it tries to converts values behind the scene (yes, you should be scared). Usually strings involved in arithmetic operations are converted to number, so :

'10' / 5 => 10 / 5 => 2

So it seems safe to assume that string representation of numbers will be treated as numbers  in arithmetic operations, right ? Not so if the + operator is involved! Remember:

'1' + '1' => '11'

Form and formula

Suppose we have a form that asks for two numbers, and some Javascript which calculates the average. Let’s say the user types ‘1′ and ‘1′:

// Form values are strings
var number1 = $('#number1').val(); // '1'
var number2 = $('#number2').val(); // '1'
var average = (number1 + number2) / 2 ; // 5.5 !!

we get 5.5 instead of 1 because (number1 + number2) is concatenation and not addition.

The workaround in that case is to convert the form values to numbers beforehand :

var number1 = Number($('#number1').val()); // 1
var number2 = Number($('#number2').val()); // 1
var average = (number1 + number2) / 2 ; // 1

What makes this especially bad, is that the program appears to be working; it just silently returns the wrong result ! So remember, be cautious when using strings and addition in Javascript…

So far 3 people have argued with us about ‘1 + 1 = 11’. Read what they've said and then add to our woes using the form below.

Bernhard Häussner · Saturday 27th June at 10:34

I got used to multiply string input by one before adding like:
var average = (number1*1 + number2*1) / 2 ; // 1
It’s a bit shorter that Number() and JS will convert.

manu · Saturday 27th June at 11:40

You’re right, I used Number() because it’s explicit, but there are shorter ways to convert your strings to numbers.

Trevor · Saturday 24th July at 19:42

var number1 = +$(’#number1′).val();

Et cetera. Leading plus is the most concise way to convert numeric strings to numbers.

Love what we’ve said? Think we’re talking nonsense? Don’t worry about being polite, just let us have it. We’re not afraid of telling you that you’re talking crap, so don’t be afraid of telling us the same.