skip to Main Content

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


  1. 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 assignment require('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.

    Login or Signup to reply.
  2. use below code then try

    const fs = require('fs');
      const path = require('path');
    
      (async (directory) => {
          console.log(await fs.promises.readdir(directory)); // Use fs.promises 
          await fs.promises.rename(path.join(directory, 'files'), path.join(directory, 'randomFiles')); // Use await with fs.promises
      })(__dirname);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search