Pigs in namespaaaace

When you’re working on a JavaScript (JS) app you’ll create loads of functions and variables. By default in JS, there is no namespacing so everything you declare is effectively in the global namespace. This can lead to issues where two or more functions or variables can easily be called the same thing and create conflicts. Take this example:

function pigs() {
  console.log("Pigs in space");
}

function pigsDance() {
  console.log("Pigs dancing in space");
}

function pigs() {
  console.log("Pigs in Mexico");
}

pigs();

The output of this will be “Pigs in Mexico”. To avoid collisions like this we can use an object to create a namespace. So reworking our above example:

var space(){
  function pigs() {
    console.log("Pigs in space");
  }
  function pigsDance() {
    console.log("Pigs dancing in space");
  }
}

function pigs() {
  console.log("Pigs in Mexico");
}

space.pigs();

This will return “Pigs in space”. By creating the object and making pigs() and pigsDancing() properties of that object, we isolate them from the global namespace that pigs() lives in.

This way, when we need our pigs in space, that’s exactly where they will be.


Posted

by