0

I'm using this doc : http://www.w3schools.com/js/js_scope.asp as an exemple.

I'm trying to get var name = snoopdog, outside the main function.

function A(){
  function B(){
    name = "snoopdog";  
  }
  //Show snoopdog
  alert(name);
}

//Show nothing
alert(name);

Ok I tried to put the nested function inside a variable, still not working.

12
  • 2
    Your first and most awful error is at using w3schools for learning other language than html/css. Commented Feb 22, 2016 at 12:25
  • 3
    "I'm use w3schools" ... that's your first mistake, the second one is telling everyone you use it Commented Feb 22, 2016 at 12:26
  • 3
    Where A() called?, Where B() called? Commented Feb 22, 2016 at 12:26
  • 1
    "//Show nothing" Wrong, shows an error in the console, (in a case the name of name variable is not name, which refers to window.name property.) Commented Feb 22, 2016 at 12:29
  • 1
    fun facts: window.name can only be a string, and it's the only variable except the storages that survives reloading. Commented Feb 22, 2016 at 12:35

2 Answers 2

1

Global variables to the rescue

var name;
A();
alert(name) //shows snoopdog

function A(){
    B();

      function B(){
      name = "snoopdog";  
    }
    //Show snoopdog
    alert(name);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you man, of course i called the function A(), thought it was implicit. This is perfect.
0

Using a var outside the main function, means you want to put it on the 'window' scope.

function A() {
    function B() {
        window.name = "snoopdog";  
    }
    //Show snoopdog
    alert(window.name);
}
//Show nothing
alert(window.name);

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.