-1
(function() {

    var sample = "sample1";

    (function() {

        // set sample variable 
        sample = "sample2";

        (function() {

            // set sample variable
            sample = "sample3";
        }());
    }());



    console.log(sample); // "sample3"
}());

so; sample name @variable console.log results "sample3"; How do I get the first variable? "sample1" ??

console.log(sample); // --> "sample1" ?? 

thank You.

yasaricli
  • 2,433
  • 21
  • 30

3 Answers3

2

Declare your variables instead of assigning to the outer one?

var sample = "sample2";

Also, why?

Ry-
  • 218,210
  • 55
  • 464
  • 476
2

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.

Community
  • 1
  • 1
phant0m
  • 16,595
  • 5
  • 50
  • 82
1

You can declare an independent sample variable in each scope:

(function() {

    var sample = "sample1";

    (function() {

        // set sample variable 
        var sample = "sample2";

        (function() {

            // set sample variable
           var sample = "sample3";
        }());
    }());

console.log(sample); // "sample1"
}());

Try it here.

phant0m
  • 16,595
  • 5
  • 50
  • 82
MyBoon
  • 1,290
  • 1
  • 10
  • 18