Poppy Poppy - 8 months ago 14
Javascript Question

Javascript code produces concatenation when addition expected?

var var1;
var var2;

var1 = readCookie('cookie_name');

var2 = +var1 + 1;


Above snippet of JS has me baffled. Unless I code the workaround oddity of '+var1', the result is '11' not 2 (assuming var1=1 and var2=1). So it seems I am getting some sort of concatenation instead of addition. My only thought is this must have something to do with the fact that var1 is a value imported from a cookie. Or it is a bug in JS. Or I am going mad. Take your pick.


Guessing readCookie('cookie_name') is returning a String. Try:

var1 = parseInt(readCookie('cookie_name'));

To get var1 as int but you may want to try the following to clean things up.

var var1 = parseInt(readCookie('cookie_name'));
var var2 = var1 + 1;

alert(var1); // should be the value of the cookie or 0

Edit: Changes made based on edited question. Makes more sense now too :]