1

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)
    }
}

1 Answers1

4

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
qrsngky
  • 2,263
  • 2
  • 13
  • 10