javascriptsumdata-layers

Sum up two values from a data layer with Javascript


I'd like to sum up to two (string) values.

The values come from a data layer. I know how to get the data out of the data layer,

return datalayer.path123.infoABC;

but I don't know how to sum them with JS.

All input is appreciated!


Solution

  • The value with the quotes is the String "1" where as the value without the quotes is the number 1. If you add those together the answer will be the String "11".

    If you want to get the sum as a number you first need to convert the String into a number. You can do this by passing it to the Number() function. Since I don't know which is the string in your case I'll just conver both to a number to be safe.

    var a = Number(datalayer.path123.infoABC);
    var b = Number(datalayer.path123.infoDEF);
    var sum = a + b;