Reputation: 16122
Is there a way to read variable values while in the console by "pulling" instead of "pushing"?
For example, say, I have somewhere in my JS:
var a = "foo";
Can I "pull" the value of a
from the console by typing in the console something like
$.a
or
$.this.a
By "pushing" I mean writing something like this in the JS:
console.log(a);
That is what I do not wish to do.
Upvotes: 0
Views: 133
Reputation: 779
If the variable is in the global scope or some object in the global scope (e.g. window
) has a reference to it, then you can read/modify it from the console by simple assignment/reference; just type MyGlobal
or MyGlobal = "foo"
into the console and execute it. In the first case, it'll print the current value, and in the latter it will modify the value. If the variable is only locally-scoped (i.e. it is just defined inside a particular function: function() { var a = "foo"; ...}
), then the console cannot access/alter it without using the script debugger (see bottom of this answer) or modifying the script (see below).
If the variable isn't in the global scope or referenced by a global object, but you can edit the script, you can easily open it up to the console. Instead of var a = "foo"
, do something like window.myOptions = {a: "foo"}
. Then from the console, you can execute window.myOptions.a
to read or window.myOptions.a = "bar"
to set the value.
If you need to read/modify the values of local variables in a script and you do not have access to change the actual script, you can use your browser's script debugger.
An easy method is to set a breakpoint at the variable you want to read/change (usually by clicking your mouse on the line number in the script debugging window; see links above for details) and then, when the script executes, it will pause when that line runs. Hovering over the variable with your mouse, or reading the info panes on the right (depending on debugger and window configuration) will show you the currently value. It also gives you a chance to modify the variable's value. You can set breakpoints at a function definition too, to read/change the parameters given to the function.
It's possible in Safari, IE/Edge, Firefox, and Chrome (basically any modern browser with good debugger tools). Firefox has a handy step-by-step guide called "Examine, modify, and watch variables": https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Examine,_modify,_and_watch_variables
Upvotes: 2