Book Image

Object-Oriented JavaScript

Book Image

Object-Oriented JavaScript

Overview of this book

Table of Contents (18 chapters)
Object-Oriented JavaScript
Credits
About the Author
About the Reviewers
Preface
Built-in Functions
Regular Expressions
Index

Scope of Variables


I t is 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, a variable defined inside an if or a for code block is visible outside the code block. The term "global variables" describes variables you define outside of any function, 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 variables.

In the next example:

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

  • Outside of the function f(), the variable local doesn't exist

var global = 1;
function f() {
  var local = 2;
  global++;
  return global;
}
>>> f();

2

>>> f();

3

>>> local

local is not defined

It is also important to note that if you...