Kowhai

Technical Blog Part 7. JavaScript scope.


  • What 'scope' is, and how it works in JavaScript.
  • There are 2 scopes in JavaScript: global and local, and in general scope is the set of variables/functions you can access.
    If a variable declared outside of a function, it is defined globally, and it means all functions can access it.

    var animal = 'penguin'; // global scope

    If a variable declared within a function, it is local to the function, and they can only be accessed within the function.

    function findAnimal() {
    var animal = "ocelot"; // local scope
    }

    Any function defined inside another function has a local scope which is linked to the outer function, so any variable declared within that function is accessible from any nested functions. Local variables are deleted when the function is completed.