Search code examples
javascriptvariablesvarstatements

Simplify Javascript Variables to Single Statement?


Wondering if it's possible to simplify the following into one variable definition:

var gpaEarned = '%%PATTERN:gpa%%'; //value for gpa is passed in dynamically
var gpa = gpaEarned.replace("Less than 2.0","1.9").replace("2.0-2.4","2.0").replace("2.5-2.74","2.5").replace("2.74-2.9","2.74").replace("3.0-3.4","3.0").replace("3.5 or Higher","3.5");

I'm looking to do something like this, if it's even possible:

var gpa = '%%PATTERN:gpa%%'.replace("Less than 2.0","1.9");

where '%%PATTERN:gpa%%' is a value that is passed in dynamically and the output of that value, is a string. This code lives inside of a creative in DoubleClick for Publishers.


Solution

  • It is possible to declare multiple variables in one statement in JavaScript.

    var one = 1;
    var two = 2;
    var three = 3;
    

    Is the same as

    var one = 1, two = 2, three = 3;
    

    ...So in your case you could declare with one statement like so:

    var gpaEarned = '%%PATTERN:gpa%%', gpa = gpaEarned.replace("Less than 2.0","1.9").replace("2.0-2.4","2.0").replace("2.5-2.74","2.5").replace("2.74-2.9","2.74").replace("3.0-3.4","3.0").replace("3.5 or Higher","3.5");
    

    You could also do this by declaring only one variable if you don't need the gpaEarned var for anything. This is also valid:

    var gpa = '%%PATTERN:gpa%%'.replace("Less than 2.0","1.9").replace("2.0-2.4","2.0").replace("2.5-2.74","2.5").replace("2.74-2.9","2.74").replace("3.0-3.4","3.0").replace("3.5 or Higher","3.5");