Summing the first 1 to n powers of 2 At a JavaScript test for a job, I was asked the question below. I believe there has to be a better way to accomplish the same result, but I couldn't find any. If some JavaScript geek would take a look and suggest a better approach I would really appreciate it:


  Given a positive integer greater or equal to 1, write a function f(n) to calculate as efficiently as possible the sum of the first 1 to n powers of 2. Do no use any buit-in function to calculate the power of a number.
  Example: if n = 3:
  
  $$ f(3)=2^1+2^2+2^3=2+4+8=14 $$


jsFiddle

function solution (n) {
    var t='';
    var q='';
    for (var i=1;i&lt;=n;i++) {
        q='';
        for (var j=1;j&lt;=i;j++) {
            q=q+'2*';
        }
        q=q+1;
        t=t+'('+q+')+';
    }
    t=t.substr(0,t.length-1);
    return eval(t);
}
EVAL, WHY!?

I really can't understand why you're using String concatenation and eval to calculate the result.

The most efficient way is to calculate \$2^{n+1}-2\$.

Additionally, your variable names are all one character long, and your code lacks spacing.

How can you tell what is t and what is q? Your variable names make no sense.

function solution (n) {
    var result = 2;
    for (var i = 1; i &lt;= n; i++) {
        result *= 2;
    }
    return result - 2;
}


Another solution is to use bit shifting: (only works if \$n &lt;= 29\$)

function solution(n) {
    return (2 &lt;&lt; n) - 2;
}