Reputation: 430
hi everyone . actually I'm newly learning Javascript . I read about scopes in javascript . then I read somewhere about namespace in Js and i was wondered if namespace is exactly the same as scope , so i searched but the results were just explained for python and I don't know if they are the same in js or not .
would someone explain the difference between scope and namespace in js ?
my definition of scope : scope is a concept in programming language that helps us to prevent variable pollution . it means we control the accessibility to the variables and function in our code . js is a function scope language it means new scopes will create if we create new function . we can declare block scope instead of function scope variable and function with the help of new keywords let , const
Upvotes: 1
Views: 293
Reputation: 1075219
"Namespace" is only used in the JavaScript specification in relation to the module namespace exotic object, which is an object created (or reused) when you do an import *
from a module. It contains properties for all of the module's named exports (and a property called default
if it has a default export).
Before JavaScript had official modules, "namespace" wasn't used in the definition of JavaScript at all. It was used informally to refer to an object that was created by a unit of code (loosely, a "module") with properties for the "exports" of that module, like this:
// ES5 code - one style of the "revealing module pattern"
var MyLib = (function() {
function internalFunction() {
// ...
}
return {
exportedFunction: function() {
// ...
}
};
})();
There, MyLib
was sometimes called a "namespace," but that was purely informal. It's just an object.
"Scope" is a region of program source code that defines a container for variables and related things. (Sometimes it's used to refer to the resulting "objects" defined by the specification, but they're more properly called lexical environment records.) For example, this source code has two explicit scopes:
function example(someParam) {
if (someParam === "some value") {
console.log("something");
}
}
The scopes are:
{}
defining the function body.{}
defining the block on the if
.(There's also the implicit scope around the function, which depends on where this source code appears — sometimes called the "ambient scope.")
At runtime, when example
is called, the specification describes creating an environment record for the function scope and later creating an environment record for the block scope. (That's just specification language; a JavaScript engine doesn't have to do it literally.) Sometimes, a scope can have two environment records defined for it (global scope is like that) but usually it's one-for-one.
Upvotes: 4