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

267
Visualizações
Why does my console return that certain variables are not defined when the code works?

//learning javascript on udemy //Here is my code (well the instructor's code but my exact replication:

const magicSquare = [ [ 2, 7, 6 ], [ 9, 5, 1 ], [ 4, 3, 8 ] ];

for (let i = 0; i < magicSquare.length; i++) {
    let row = magicSquare[i];
    let sum = 0;
    for (let j = 0; j < row.length; j++) {
        sum += row[j];
    }
    console.log(`${row} summed to ${sum}`);
}

//So before i had wrote the last line: console.log(${row} summed to ${sum}); i would type in "sum" or "row" into my console just to check to make sure that it was working properly, and in return the console god would return to me:

Uncaught ReferenceError: sum is not defined

//so each time i got undefined i thought i must be doing something wrong so i kept going back and looking at the instructor's code and then at mine, and i was getting super frustrated because i knew we had the exact same thing, so i just finally decided to finish the whole thing and see if it ran. Sure enough, as soon as i put the last line which is the template literal; at the bottom it worked! But still if i type in : row or sum (without quotations of course) into the console it returns undefined! How can something work and be undefined? It was a great gaslighting operation..

//Is it because these variables are located within the loop? If i define them outside the loop they show up in my console.

//also stackoverflow is telling me CTRL + K my code for formatting, not sure if im doing this correctly, new user, first question, no programming experience. Thank you!

about 4 years ago · Juan Pablo Isaza
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