Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda