0

I have an IIFE with a nested function inside. There is a word variable both inside and outside the nested function. How can I access the word variable outside the nested function instead of the inside one?

Code:

(function (){

    let word = "Hello";

    function sayHello(){
        let word = "Greetings";
        console.log(word + " Everyone!"); // This is using the inside word variable instead of the outside one. How can I specify JS to use the outside one instead?
    }

    sayHello();

})();
Bill
  • 553
  • 1
  • 7
  • 19
  • 1
    To reach them both directly, one or the other will have to be renamed. Related: [Variable shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) and [JavaScript Access Local Variable with Same Name in Inner and Outer Scope](https://stackoverflow.com/questions/4001414/javascript-access-local-variable-with-same-name-in-inner-and-outer-scope) – Jonathan Lonowski May 13 '18 at 05:42

1 Answers1

2

Pass the outer variable as a parameter so you can reference it separately from the inside variable:

(function() {
  let word = "Hello";
  function sayHello(outerWord) {
    let word = "Greetings";
    console.log(outerWord + " Everyone!");
  }
  sayHello(word);
})();

Alternatively, simply give the variables different names, if you're allowed - shadowing is usually a bad idea for exactly this reason.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320