0

I want to print the global scope variable declared using let which is also declared with same name inside a function.

I have used window object but it kept on saying window is not defined.

var globalLet = "This is a global variable";
 
function fun() {
  var globalLet = "This is a local variable";
  console.log(globalLet); //want to print 'This is global variable' here.
}
fun();
Phil
  • 157,677
  • 23
  • 242
  • 245
immukul
  • 87
  • 11

3 Answers3

1

Use this.varname to access the global variable

var globalLet = "This is a global variable";

function fun() {
  var globalLet = "This is a local variable";
  console.log(this.globalLet); //want to print 'This is global variable' here.
}
fun();
ellipsis
  • 12,049
  • 2
  • 17
  • 33
1

When you set the value of this to null then it will always map to the global object (in non-strict mode).

Here just declaring an anonymous function and setting this as null and calling it immediately by passing the property of the global object globalLet will always return the global value.

Caution: This won't work in strict mode, where this will point to null.

var globalLet = "This is a global variable";
 
function fun() {
  var globalLet = "This is a local variable";
  globalLet = (function(name){return this[name]}).call(null, "globalLet");
  console.log(globalLet); //want to print 'This is global variable' here.
}
fun();

According to the ES5 spec

15.3.4.4 Function.prototype.call (thisArg [ , arg1 [ , arg2, … ] ] ) # Ⓣ Ⓡ When the call method is called on an object func with argument thisArg and optional arguments arg1, arg2 etc, the following steps are taken:

If IsCallable(func) is false, then throw a TypeError exception.

Let argList be an empty List.

If this method was called with more than one argument then in left to right order starting with arg1 append each argument as the last element of argList

Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and argList as the list of arguments.

The length property of the call method is 1.

NOTE The thisArg value is passed without modification as the this value. This is a change from Edition 3, where a undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value.

Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
1

Use this keyword in global context, it is bound to global object.

var globalLet = "This is a global variable";
 
function fun() {
  var globalLet = "This is a local variable";
  console.log(this.globalLet); //want to print 'This is global variable' here.
}
fun();
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24