Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using var to intentionally leak a variable

Is the following pattern ok in javascript, or is this frowned upon? And if the latter, what would be a better approach?

function arithmetic_sum(n) {
    for (var [i, sum] = [0, 0]; i <= n; sum += i++);
    return sum;
}

console.log(arithmetic_sum(10));
// 55

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is valid JavaScript.

Some people may like that, but it’s a bit outdated and mixing old and new styles (var, but in combination with destructuring).

Also having code inside the interation clause of the for loop can be confusing.

I would prefer this instead:

function arithmetic_sum(n) {
    let sum = 0;
    for (let i = 0; i <= n; i++) {
      sum += i;
    }
    return sum;
}

console.log(arithmetic_sum(10));
// 55
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading