'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 1:[1]
It really depends on the person to be honest. Some people will like this pattern because it makes the code shorter but in my personally opinion it makes the code harder to understand.
The reason this works is because of javascript hoisting. You can read more about this here. https://www.w3schools.com/js/js_hoisting.asp
Now, if you were to switch this code to use let this code would break.
I think its also important to understand how var differs from let & const.
This article explained the differences very good https://medium.com/@codingsam/awesome-javascript-no-more-var-working-title-999428999994
I personally would write this code like this:
function arithmetic_sum(n) {
let sum = 0;
for (let i = 0; i <= n; i++) sum += i;
return sum;
}
console.log(arithmetic_sum(10));
// 55
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcellino Ornelas |
