1
Prakash
5y

Unable to understand difference between variable declaration and definition. Can anyone help?

Comments
  • 2
    Const declared vars cannot be redeclared in the same scope.

    Something else already declared a variable named graph. Try "let someOtherGraph"
  • 0
    @SortOfTested but why it is throwing an error when I am trying to access `graph` value?
  • 0
    @Prakash
    graph is being indirected by something. Possibly a proxy or a getter
  • 0
    @SortOfTested Can you explain it further?
  • 1
    A special rule applies when you declare a variable with let.
    You can't redeclare a variable declared by let, for example let x =1; let x = 2; doesn't work.
  • 0
    @PrivateGER See 2nd line. I am unable to access the value of `graph`
  • 0
    Try to JSON.stringify it.
  • 0
    @PrivateGER unable to reproduce the issue again. Will try again tomorrow.
  • 0
    My guess is you ran `let graph` earlier which declares but doesn't define it.

    The assignment (definition) fails because you're trying to re-declare it which isn't allowed. Drop the `let` for re-assignment.

    Since you're in your browser's dev tools, reloading the page clears variables and lets you assign using `let` again
  • 0
    @DustInCompetent kindly read the second line, I am unable to access its value. Why is that happening?
  • 3
    declaration:
    let myVar;
    var myVar;

    definition:
    const myVar = null;
    let myVar = null;
    var myVar = null;

    You cannot re-declare any variable in the same scope (a definition implies an declaration).

    Your interactive console is also one scope (basically like the inspector-stylesheets, each line emulates a js file and the browser magic preserves your scope).

    You can easily avoid this by using a collection var (var global ={}) or simply adding shit to you window.

    Alternatively, you can also make an anonymous self-calling function that will receive the already declared variable. You (should) then be able to overwrite it - but for that scope, not affecting the parent.

    Basically {} gives you a new scope. You can also declare the same variable name if you use a case 123: {doThat()}, which you cannot if you leave the curly braces.

    Last tip: Store elements via the inspector, so they are temp1, temp2 and so on...
Add Comment