Scope of variables

It's important to note, especially if you have come to JavaScript from another language, that variables in JavaScript are not defined in a block scope, but in a function scope. This means that if a variable is defined inside a function, it's not visible outside of the function. However, if it's defined inside an if or a for code block, it's visible outside the block. The term global variables describes variables you define outside of any function (in the global program code), as opposed to local variables, which are defined inside a function. The code inside a function has access to all global variables as well as to its own local ones.

In the next example:

  • The f()function has access to the global variable
  • Outside the f()function, ...

Get Object-Oriented JavaScript - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.