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?
It is because you didn’t declare it with a
varkeyword.If you don’t use the
varkeyword, it will be in the global scope. If you do usevar, it will be in the function scope:You can declare named functions without the
varkeyword, and they will still be in the local scope: