UX Design and Development course

Local and Global variable scopes

Understanding which variables are accessible in any given part of your JS code is critical to avoiding bugs and writing clear code. Here's the basics...

Functions act as a way of creating a new scope:

Global variable - a var that is accessible OUTSIDE all functions

Local variable - a var accessible only INSIDE a function

A local variable will not be accessible in any scope outside of the scope in which it was defined.

// This is a global var, accessible in every scope
var wife = 'Jennifer';

function outPut() {
  // This is a local var, accessible only in this function's scope:
  var daughter = 'Zoe';

  /*
    WATCH OUT: With no "var" keyword, variables are created in the global scope. Always use var.
  */
  son = 'Micah' // ANTIPATTERN, not using the var keyword

  // run the functions
  console.log(wife);
  console.log(daughter);
  console.log(son);
}

Notice in the view how the var of daughter does not appear This is because daughter is scoped to the outPut function

outPut();
console.log(wife);
console.log(son);
console.log(daughter); // This causes an error, script halted.

Play with code

JS Bin