JavaScript Variable Scope: Function Level vs Block Level

By Xah Lee. Date: . Last updated: .

Here's a summary of JavaScript variable scope issues:

For variable declared with var:

  1. Curly bracket {} doesn't make variables inside it local.
  2. Variable are local to just functions, and is lexically scoped. For example, function () { /* scope here */ }

Variable declaration and assingment:

  1. declared and assigned → good.
  2. declared and unassigned → has default value of undefined.
  3. undeclared and assigned → implied global variable. (not exactly the same as declared global variable. Their configurable attribute's value is different.)
  4. undeclared and unassigned (and accessed) → ReferenceError.

Global Variable = Property of Global Object

Global variable is just property of the global object.

In web browser, the global object is window . 〔➤see JavaScript: Browser Window Object, Document Object Model

// global variable is a property of global object
var xx = 3;
console.log(window.xx); // 3

(copy and paste the code and try it in your browser's JavaScript console. 〔➤see JavaScript: How to Use Browser's JS Console〕)

// global variable is a property of global object
window.yy = 4;
console.log(yy); // 4

Undeclared Variable (aka Implied Global)

When a variable is assigned but not declared, it is a global variable. This is sometimes called “implied global”.

// example of undeclared variable

function f () { x = 4; return 1; }
f();

// this is a global variable
console.log(x); // 4

// it's a property of the global object
// in browser, the global object is “window”
console.log(window.x); // 4

// in node.js, the global object is “global”
console.log(global.x); // 4

Difference Between Implied Global and True Global Variable

Property's configurable attribute means whether the property can be deleted (For example, delete window.x) and whether its attributes can be changed. 〔➤see JavaScript: Property Attributes: Writable, Enumerable, Configurable

// difference between declared and undeclared variable

var x = 1;
console.log(Object.getOwnPropertyDescriptor(window, "x"));
// Object {value: 1, writable: true, enumerable: true, configurable: false}

y = 1; // undeclared
console.log(Object.getOwnPropertyDescriptor(window, "y"));
// Object {value: 1, writable: true, enumerable: true, configurable: true}

(Note: as of , in Firefox, if you run code in JavaScript console, undeclared var's configurable property is the same as declared global variable (presumably for programer convenience). But in Google Chrome's JavaScript console, it behaves by spec.)

Accessing Undeclared and Unassigned Variable ⇒ ReferenceError

x; // ReferenceError: x is not defined

var y; // unassigned var has value of 「undefined」
console.log(y);           // prints undefined

Function-Level Scope

// curly brackets doesn't scope

function f ()  {
    var n = 3;
    {
        var n = 4;
    }
    return n;
};

console.log(f());               // 4

Using Function to Emulate Block Scope

You can emulate block scope like this:

(function(){
    var x; // local var x
    // ...
}());

This will create a function, and immediately evaluate it. Here's a example.

function f ()  {
    var n = 3;
    (function(){
        var n = 4;
    })();
    return n;
};

console.log(f()); // prints 3

Function Scope as Namespace

JavaScript (ES5) does not have modules or namespace. One hack to achieve namespace is wrapping the entire source code of your package inside a function. Like this:

(function nicePackage () {
    // your source code here
})();

This way, when your package/file is loaded, it only introduces one name into the global space.

Note: your function should start with a lowercase letter, because uppercase function names are constructors by convention. 〔➤see JavaScript: Operator “new”

JavaScript variable topics

  1. JavaScript: Variable
  2. JavaScript: Variable/Function Declaration Order, Name Hoisting
  3. JavaScript Variable Scope: Function Level vs Block Level
  4. JavaScript: let and const Declarations (ES2015)

Function topics:

  1. JavaScript: Define Function
  2. JavaScript: Function Optional Parameters
  3. JavaScript: Variable/Function Declaration Order, Name Hoisting
  4. JavaScript Variable Scope: Function Level vs Block Level
  5. JavaScript: Function Declaration vs Function Expression
  6. JavaScript: Closure
  7. JavaScript: Functional Programing
  8. JavaScript: f.call f.apply f.bind
  9. JavaScript: Function Constructor
  10. JavaScript: Function Argument Default Value (ES2015)
  11. JavaScript: Function Rest Parameters (ES2015)
  12. JavaScript: Arrow Function (ES2015)
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.