Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to console.log the content of a closure

I would like to see the content of a closure in JavaScript.

In the following code, I would like to see the closure of the function closure_f returned by the anonymous function. The local scope of the anonymous function must be stored somewhere, I would like to see where it is stored. How can this be done in Node or in the browser?

var closure_F = (function(){
var info = "info-string";
var f1 = function(){
    console.log(info);
};
return f1;
}());

closure_F(); // logs 'info-string' as expected.
console.log(closure_F); // This did not provide any valuable information.
like image 853
nnkparikh Avatar asked Sep 19 '25 04:09

nnkparikh


1 Answers


WAY 1: Internal property [[Scope]]

You can modify your code by adding console.dir and then run it in the Chrome Dev Console:

var closure_F = (function(){
  var info = "info-string";
  var f1 = function(){
    console.log(info);
  };

  return f1;
}());

closure_F();
console.dir(closure_F); 
// console.dir prints all the properties of a specified JavaScript object

If you open the console you will see that it prints all the properties of the object (function), including the internal property [[Scopes]].

This internal property [[Scopes]] will contain any surrounding scopes of the closure_f, and its closure. See example:

Scope internal property containing the Closure

Note: [[Scope]] is an internal implementation of JS and cannot be programatically accessed within the program.



WAY 2: Setting a breakpoint - debugger

Another way to see the Closure of a function is to add a debugger statement and create a break point in the function who's closure you want to inspect. As an example you can run this in the console:

function createClosure (){

  var secret = "shhhhh";

  return function inner(){
    debugger;
    console.log(secret);
  };
  
};

var innerFunction = createClosure();

innerFunction();

www.ecma-international.org >> [[Scope]] >> Table 9

like image 119
ross-u Avatar answered Sep 20 '25 19:09

ross-u