1

I've had this issue pop up in one form or another over the years, and I finally figured out how to put it to words. Consider the following code:

import React, {Component} from "react";
import aFunction from "./Function";

export default class SomeComponent extends Component{
  constructor(props){
    super(props);
  }

  render(){
    console.log(aFunction);
    debugger;
    return(
      <div>some stuff</div>
    )
  }
}

The console.log() call will print information about aFunction, but if I type "aFunction" into the browser console I get a reference error. Why does this happen? Shouldn't console.log and the browser console via debugger have access to the same scope?

EDIT: I should clarify that I'm getting a reference error after allowing the "debugger" to occur before typing "aFunction". I'm not trying to call up block scoped variables after render() has completed.

  • Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Drew Reese May 05 '20 at 23:59
  • It didn't quite answer it, but I needed the refresher so it's still really helpful, thanks. After reading that I realized I had forgotten there was a scope difference between var and let/const... – Van-Nostrand May 06 '20 at 01:12
  • Well, I thought it'd help explain why `console` is on the `window` object or otherwise in global scope whereas `aFunction` is imported and has more localized scope. You can add `aFunction` to the global object and it'd be accessible in the browser's console. – Drew Reese May 06 '20 at 03:05

1 Answers1

1

It's an engine optimisation. Variables are invisible if they are not needed.

You can use a small hack to prevent it.

eval('debugger');

And when you use console.log you have it in your scope. So, you can use another hack:

const temp = smthFromParentScope;
debugger;

It happens when you are in a nested function and there are no functions that have a reference to them.

function foo() {
    const a = 1;
    const b = 2;

    function bar() {
        console.log(a); // now we have a ref
    }

    function baz() {
        debugger; // here we can see only 'a'
    }
}
Mark Partola
  • 654
  • 3
  • 10