2

I'm trying to understand how can namespace be implemented in JavaScript. I'm checking out How do I declare a namespace in JavaScript?.

One of the answers mentioned the following TypeScript code.

namespace Stack {
    export const hello = () => console.log('hi')
}

Stack.hello()

is compiled to the following JavaScript

var Stack;
(function (Stack) {
    Stack.hello = () => console.log('hi');
})(Stack || (Stack = {}));

However, I find it hard to understand the above syntax, could someone explain how does it work? For example, how does the following work?

(function(Stack) {...})(...)
(Stack || (Stack = {}))
Stephen Fong
  • 697
  • 5
  • 17
  • 1
    (Stack || (Stack = {}) means if Stack is undefined or null, set Stack = {} as param. Now inside the function, everything inside will be instantiated with Stack object. Like Stack.hello, Stack.whateverExistsInNamespace – subodhkalika Jul 03 '22 at 03:22

1 Answers1

3

var Stack;
(function (Stack) {
    Stack.hello = () => console.log('hi');
})(Stack || (Stack = {}));

Stack.hello();

It's a self-executing anonymous function. You can check this document for some insights.

For a more understanding version, you can imagine it like below

var Stack;

//naming the function
//`Stack` here is not related to the global `Stack` because the function parameter scopes this variable
function anonymousFunction(Stack) {
    Stack.hello = () => console.log('hi');
}

//replace for `Stack || (Stack = {})`
if(!Stack) {
   Stack = {} //it's a reference value, so if we have any changes inside a function, it will be applied to `Stack` as well
}

//execute the function/namespace to add `hello` to `Stack`
anonymousFunction(Stack); 

Stack.hello();
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
  • is Stack || (Stack = {}) saying if Stack has been initialized then use Stack as the argument, otherwise, initialize Stack to {} and use it as the argument? – Stephen Fong Jul 03 '22 at 03:09
  • actually, it assigned an empty object to Stack if Stack is null, because we cannot assign `hello` to `null` value. You can see the full version of that code in my modified answer. @StephenFong – Nick Vu Jul 03 '22 at 03:12