Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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,870 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!