Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!