When I write const path = require('path')
outside the IIFE function I can’t access it inside, but when I write it inside the function I am able to access it. Can anyone explain why is this happening?
Can’t access in this case:
const path = require('path')
(async (directory) => {
console.log(await fs.readdir(directory))
fs.rename(path.join(__dirname, 'files'), path.join(__dirname, "randomFiles"))
})(__dirname)
Can access in this case:
(async (directory) => {
const path = require('path')
console.log(await fs.readdir(directory))
fs.rename(path.join(__dirname, 'files'), path.join(__dirname, "randomFiles"))
})(__dirname)
Why?
I was expecting it to work on both cases.
2
Answers
If we take a look at lexical scoping, in the first case, the path variable is declared in the outer scope, and the IIFE is a nested block. According to lexical scope rules, the path variable should be accessible within the IIFE because it’s in the outer scope.
So, why can’t we access path in the first case?
The reason is that JavaScript has a concept called "hoisting". Hoisting means that variable declarations are moved to the top of their scope, regardless of where they’re actually declared. However, the assignment of the variable is not hoisted, only the declaration.
In the first case, the
const path = require('path')
declaration is hoisted to the top of the outer scope, but the assignmentrequire('path')
is not executed until the line is reached. When the IIFE is executed, the path variable has been declared, but it hasn’t been assigned a value yet, so it’s undefined.In the second case, the
const path = require('path')
declaration is within the IIFE, so it’s not hoisted out of the IIFE. The assignment is executed when the line is reached, and the path variable is properly initialized within the IIFE.use below code then try