Ufuk's Blog

Global, local and lexical scope

☕️ 1 min read

Think of a context has functions and variables in it and we can access them. That context is a scope. There are three kinds of scope: global, local and lexical. Let’s see what they all about!

Global scope

If you declare your functions and variables outside of a function, you can access them inside of that function.

// This variable below is in the global scope
var name = 'Ufuk';

var logName = function() {
  // You can access the "name" variable from here
  console.log(name);
};

logName();

// Not surprisingly you can access it from here too!
console.log(name);

Local scope

If you declare your functions and variables inside of another function you can only access them inside of that function.

var logName = function() {
  // "name" is a local variable of logName()
  var name = 'Ufuk';

  // you can access it from here
  console.log(name);
};

logName();

// you can't access it from here!
console.log(name);

Lexical Scope

In JavaScript it is possible to declare a function inside of another function. Let’s declare two functions and call them parent and child functions and see what lexical scope is.

var logNames = function() {
  // this variable is in the lexical scope
  var name = 'Ufuk';

  var logName = function() {
    // this will log "Ufuk" in the console
    console.log(name);

    // this variable is in the local scope of logName()
    var anotherName = 'John';
    // this will log "John" in the console
    console.log(anotherName);
  };

  logName();

  // this will also log "Ufuk" in the console
  console.log(name);
  // you can't access that from here
  console.log(anotherName);
};

logNames();

That’s it for now, I’ll see you on another post!