-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.

3
  • 1
    There's no 'first variable' here: there's only a single variable. Commented Sep 29, 2012 at 15:17
  • 1
    dynamic variable content, but ?? so sample @variable {{ name.tag }} ?? Commented Sep 29, 2012 at 15:18
  • learn how scopes work... otherwise, you're wasting our time. Commented Sep 29, 2012 at 15:20

3 Answers 3

2

Declare your variables instead of assigning to the outer one?

var sample = "sample2";

Also, why?

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.