JavaScript

What is Namespace? (JavaScript)

In an article shared by Mr. McFarland the article talks about scope and namespace but it doesnt explain namespace. I feel like I just watched a real good movie that ended with a cliff hanger. Can someone explain what a namespace is? if i take all the javascript courses offered by teamtreehouse will i eventually learn about it?

1 Answer

Dave StSomeWhere
Dave StSomeWhere
19,768 Points

This MDN Doc should help.

I think of a namespace as the name of the scope. So if you define a variable, function, class or object, you are defining it in a namespace (the Global Namespace is the default for JavaScript). When you create a new object (like a function) you are creating a new scope and the namespace is the object name. There are additional features and different languages have various capabilities but I consider the above the basic core concept.

For a simple basic script example:

let globalNamespaceVar = 'example variable in the Global NameSpace';
let var1 = 'var1 variable in the Global NameSpace';

const objExample = {};
objExample.var1 = 'Object property var1 in the objExample NameSpace';

function foo(var1) {
    console.log(var1);
}

// don't need prefix for variables in global name space
console.log(globalNamespaceVar);
console.log(var1);

// using same name var1 in the objExample namespace
console.log(objExample.var1);

//using same name var1 in the foo function namespace
foo('foo function namespace var1');

// output
example variable in the Global NameSpace
var1 variable in the Global NameSpace
Object property var1 in the objExample NameSpace
foo function namespace var1

Hopefully this helps get you started.

@Dave StSomewhere thank you so much!