An assignment changes the value that you have stored in a variable. It's not possible to get the old value back.
Referencing variables
Whenever you reference a variable – read or write to it, that is – JavaScript will travel up the scope chain until it finds a variable of that name, otherwise it will create it in the topmost scope: window
, the global scope.
Declaring variables
var
declares a new variable in the current scope. If you were to prepend each assignment to sample
with var
, the variables would shadow 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.
What your code essentially does
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 exactly what your code does):
var sample = "sample1";
sample = "sample2";
sample = "sample3";
console.log(sample);
Obviously, it's going to print sample3
and you can't magically have an old value reappear.