Reputation: 193
Might be a silly question but it still got me a bit stuck, not being 100% sure of the answers.
So I have an index.html file which calls a function in an example.js-file (just adding it for clarification):
function sinusGraph() {
var plotstart = 0,
plotrange = 20,
stepsize = 0.5; // not in use right now
var yValues, xValues;
function sinusValues(startinput, stopinput)
{
return d3.range(startinput, stopinput+1).map(function(i)
{
return Math.sin(i);
})
};
function xAxisValues(startinput, stopinput)
{
return d3.range(startinput, stopinput+1).map(function(i)
{
return i;
})
};
xValues = xAxisValues(plotstart, plotrange);
yValues = sinusValues(plotstart, plotrange); };
Writing, for example, "xValues" with the variables declared in the browser's returns "xValues is not defined(...)".
Removing "var xValues" letting it be a global variable does return the value.
My questions:
The browser's Tool Console can't see non-global variables within functions?
If that is the case, then is this a good tool to look for potential global variables that you have created by mistake?
Upvotes: 0
Views: 337
Reputation: 816262
The browser's Tool Console can't see non-global variables within functions?
Yes.
Here is why it can't work: Local variables of a function only exist while the function is running. Code you type into the console will either be executed before or after the function is executed.
Even if you were able to access local variables after a function was executed:
varname
in the console? The inital value, the last value or all values?You can only inspect the current state of your application.
If that is the case, then is this a good tool to look for potential global variables that you have created by mistake?
No. You should use a linter such as ESLint that warns you if you forget e.g. a var
declaration. Also enable strict mode: Assignments to undeclared variables will throw an error then.
Is there any way to view these variables in the browser's tool console, other than using console.log(myVariable) within the function where it is declared?
Set a break point in your code, either through the devtools or via debugger
. Code execution will pause at the breakpoint and the console has access to everything that is accessible at the breakpoint.
Upvotes: 2
Reputation: 943108
The console has to run the code some scope (and it can't access a scope defined by a function that isn't running anyway).
Set a breakpoint inside the function, to pause execution there. When that breakpoint is triggered, the console's scope will be to that function.
Upvotes: 1