As noted elsewhere, you can list all user-defined symbols with this:
Names["Global`*"]
But I'd like to find just my global variables (I'm in the middle of some hairy debugging), not my function definitions. Something like this is close:
Select[Names["Global`*"], Head@Symbol[#]=!=Symbol && Head@Symbol[#]=!=Function&]
But that misses variables whose value is a symbol (perhaps I have x = Pi
).
I could probably beat that thing into submission but maybe there's a cleaner, more direct way?
Once setup, open jslinter and go to Options->check everything on the left column except "tolerate unused parameters". Then run jslinter on the webpage and scroll down in the results. You will have a list of unused variables (global and then local to each function).
There are three different ways to classify global variables: by the ownership of the variable, by the scope of the value, and by the method used to maintain the value.
A global variable is a variable that is declared in the global scope in other words, a variable that is visible from all other scopes. In JavaScript it is a property of the global object.
Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function.
If we consider any symbol with an own-value as a "variable", then this will do the trick:
ClearAll[variableQ]
variableQ[name_String] := {} =!= ToExpression[name, InputForm, OwnValues]
Select[Names["Global`*"], variableQ]
Note that this technique will fail on read-protected symbols and will misidentify some forms of auto-loaded functions.
Edit 1
As @Szabolcs points out, the definition of variableQ
can be simplified if ValueQ
is used:
variableQ[name_String] := ToExpression[name, InputForm, ValueQ]
Edit 2
As @dreeves points out, it might be desirable to filter out apparent variables whose values are functions, e.g. f = (#+1)&
:
variableQ[name_String] :=
MatchQ[
ToExpression[name, InputForm, OwnValues]
, Except[{} | {_ :> (Function|CompiledFunction)[___]}]
]
This definition could be easily extended to check for other function-like forms such as interpolating functions, auto-loaded symbols, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With