Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda