Sourabh Yadav
Sourabh Yadav

Reputation: 31

Differentiate between var from above block and let variable in a block with the same name in javascript

I have a situation like this:

var menu="VarMenu"
{
  let menu="LetMenu";
  console.log(menu);
}

The problem is that I want to access the menu variable declared with var with value "VarMenu" inside the block. Is it possible? A similar(but conceptually different) way in C++ is to use the scope resolution operator. Please Help. Hope the question is not a duplicate.

For those who are wondering what it's need is.. Well I had written a menu variable earlier and now I need all of the code that I used inside a block for it but assign to a new let variable(which is a problem that I came across while making menu interface.. I just need another enclosing div for the menu content).

Upvotes: 0

Views: 76

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074365

The problem is that I want to access the menu variable declared with var with value "VarMenu" inside the block. Is it possible?

Not if the code shown is anywhere other than global scope¹ (so: in a function, in a module, etc.). The menu inside the block completely shadows the menu outside the block. You cannot access it.

Your best bet is to change the name of one or the other.

Just for completeness, a very much worse idea is to define a function that can get the outer menu's value. (E.g., function getMenu() { return menu; } defined outside the block and called within it.) I don't recommend it if you can avoid it. :-)


¹ If the code shown is at global scope, var menu creates a global variable, and var globals are also properties of the global object, which you can access via globalThis (in modern environments) or window (on browsers). So you could use globalThis.menu or window.menu inside the block to access it. But only if the code shown is at global scope.

Upvotes: 2

Related Questions