Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>An assignment <em>changes</em> the value that you have stored in a variable. It's not possible to get the old value back.</p> <h2>Referencing variables</h2> <p>Whenever you reference a variable &ndash; read or write to it, that is &ndash; JavaScript will travel up the <a href="https://stackoverflow.com/questions/111102/how-do-javascript-closures-work">scope</a> <a href="https://stackoverflow.com/questions/1484143/scope-chain-in-javascript">chain</a> until it finds a variable of that name, otherwise it will create it in the topmost scope: <code>window</code>, the global scope.</p> <h2>Declaring variables</h2> <p><code>var</code> declares a new variable in the current scope. If you were to prepend each assignment to <code>sample</code> with <code>var</code>, the variables would <a href="https://stackoverflow.com/questions/5373278/variable-shadowing-in-javascript">shadow</a> the outer ones. Why? Let's recall that JavaScript travels up the scope chain when you reference a variable. Obviously, it will find the ones in the nested scopes first, stopping it from looking further in parent scopes.</p> <h2>What your code essentially does</h2> <p>Keeping in mind what happens when you reference a variable, we can transform your code to this, which is semantically equivalent (i.e. it is <em>exactly</em> what your code does):</p> <pre><code>var sample = "sample1"; sample = "sample2"; sample = "sample3"; console.log(sample); </code></pre> <p>Obviously, it's going to print <code>sample3</code> and you can't magically have an old value reappear.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload