Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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