0

I want to intercept and log a statement, everytime a variable or property is declared

As an example after I following code:

let name = "John";
let greet = function(personName) { 
    let greeting = 'hello';
    return greeting + ' ' + personName;
}
greet(name);

I should get following log:

name was created in window scope
greet was created in window scope
personName was created in greet scope
greeting was created in greet scope

Is this possible in javascript?

dasfdsa
  • 7,102
  • 8
  • 51
  • 93
  • 3
    Is this [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? – VLAZ Sep 23 '22 at 15:21
  • 1
    This is not a XY problem. This is exactly what I want to do. Thanks :) – dasfdsa Sep 23 '22 at 15:22
  • I wouldn't be surprised if doing this required digging into the internals of the browser and JavaScript engine itself. Why do you want to do this in the first place? What's the problem you're trying to solve? – David Sep 23 '22 at 15:23
  • Yes, you need to log it by checking it programmatically – kavigun Sep 23 '22 at 15:23
  • 1
    Without modifying the engine, or altering the premises slightly, I'd say this isn't possible. – ASDFGerte Sep 23 '22 at 15:23
  • 1
    You can't get the event something is declared, but you can get the event when a property on an object changes, is deleted, iterated over, etc with [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). – kelsny Sep 23 '22 at 15:23
  • What is the problem you're trying to solve and how are you doing it? are you writing a test? how do you import the code file – Haroon Azhar Khan Sep 23 '22 at 15:23
  • @HaroonAzharKhan I am trying to create a tree of scopes object. Where each object will have details of property declared – dasfdsa Sep 23 '22 at 15:29
  • This might help what you are trying to do. I can't comment, [listening for var changes](https://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript) – spac3man Sep 23 '22 at 15:30

1 Answers1

3

No, this is not possible in JavaScript.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • Is it also not possible by parsing the source code? IDEs know variable scope very well. – dasfdsa Sep 23 '22 at 15:35
  • 2
    You can most definitely use a library like acorn or others which generates AST ([see here](https://astexplorer.net/#/gist/995133dc17bd5a73e24c5f1b3a5cce1e/b06b4d9f3315b0f7af21f7ecb286726ddd96526c)) which can then be programmatically analysed. But that's not what the question asked. – VLAZ Sep 23 '22 at 15:38
  • 1
    You have opened a whole new world to me good sir. This is almost exactly I was asking. – dasfdsa Sep 23 '22 at 15:50
  • The only thing is, [here](https://astexplorer.net/#/gist/995133dc17bd5a73e24c5f1b3a5cce1e/f98a95bc37a1c41fb8b723d5f96f2fb09dad0dc5), how do I know name in L5 is the one declared in L4 and not the one in L1 – dasfdsa Sep 23 '22 at 15:53