What is the scope of this JavaScript function

JavaScript has function level scope. So let’s go through the code. You define two functions in the code. The first one is a no-name function that is passed as a callback to $(document).ready. Let’s call it callback function. a is defined inside of this callback function and is therefore in local scope. So a can only be referred to from inside of the callback function.

You invoke a after defining it and see the alert. Then you try to get the reference to a from the global object (everything that is defined globally goes into window in the browser). Since a isn’t defined globally, you cannot retrieve it from window. Actually you retrieve null and you see TypeError: window.a is not a function on the console when trying to invoke it with ().

Browse More Popular Posts

Leave a Comment