0

I thought one of the point of functions in javascript was to provide scope. Things defined in a function were only available inside the function.

function cat(name) {
    talk = function() {
        alert(" say meeow!" )
    }
} 

talk()

I would expect the above code to fall over because talk should not be visible. But it is, why?

1

3 Answers 3

4

It is because you didn't declare it with a var keyword.

If you don't use the var keyword, it will be in the global scope. If you do use var, it will be in the function scope:

function cat(name) {
  //anonymous function assigned to the local variable talk
  var talk = function() {
    alert(" say meeow!" )
  };
}

You can declare named functions without the var keyword, and they will still be in the local scope:

function cat(name) {
  //local talk function
  function talk() {
    alert(" say meeow!" )
  };
}
Sign up to request clarification or add additional context in comments.

Comments

2

You haven't actually defined the variable in any scope. So it default to global scope.

function cat(name) {
    var talk = function() { // <-- added var
        alert(" say meeow!" )
    }
} 

talk() // fail

JavaScript allows you to use variables without defining them, this makes the programming language easier to learn and more flexible. I wouldn't recommend you make use of this feature though. Always define your variables.

Comments

2

inside of a function, you have to declare variables with "var" or they are declared globally. so you would do:

function cat(name) {
    var talk = function() {
        alert(" say meeow!" )
    }
} 

talk() // error: undefined

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.