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

142
Visualizações
why dont i have to declare the variable in javascript for loop

in javascript, why are we able to use variables that havent been declared (i.e. const, let, var) in the for loop? example code below:

function testFunc(items) {
    for (item of items) {
        console.log(item)
    }
}

I would expect the above code to error out. Dont we need to declare the variable with one of the const, let and var keywords? Example below:

function testFunc(items) {
    for (const item of items) {
        console.log(item)
    }
}

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In non-strict mode, it will not throw an error. It will just create a global variable item for the window:

function testFunc(items) {
    for (item of items) {
        console.log(item)
    }
}
testFunc([1,2,3])
console.log(window.item) //property created in the window object
console.log(item) //global variable

Even though you cannot get the value of item before it's assigned (ReferenceError), if you have an assignment like item=1 in non-strict mode, it will create a variable (global scope) if it's not yet defined. The for loop in this case does the item=1, item=2, item=3. So, getting the value of the item (as in console.log(item)) is allowed.
And as you can see from the output, the value of item after the loop is 3.


But if you just add a "use strict" statement, it throws an error

"use strict"
function testFunc(items) {
    for (item of items) {
        console.log(item)
    }
}
testFunc([1,2,3]) //throws ReferenceError

about 4 years ago · Santiago Trujillo 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