Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a namespace a must for local JavaScript functions?

I agree that using a namespace is essential for JavaScript libraries, but what about those functions that reside in HTML files in a script tag? Basically these are "local" functions that are never shared with any other pages. Do you guys still use a namespace for those? If so, do you use the same namespace as your shared custom library?

like image 343
Tom Tucker Avatar asked Feb 08 '11 01:02

Tom Tucker


People also ask

What is the use of namespace in JavaScript?

JavaScript Namespaces: Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.

Are there namespaces in JavaScript?

JavaScript does not provide namespace by default. However, we can replicate this functionality by making a global object which can contain all functions and variables.

What is the global namespace in JavaScript?

In JavaScript, it is nothing but a single global object which will contain all our functions, methods, variables and all that. Here ' MYAPPLICATION ' is acted as a JavaScript namespace and the only global object which contains all other items.

How do you define a function in JavaScript?

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). Function names can contain letters, digits, underscores, and dollar signs (same rules as variables). The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)


2 Answers

I would say that a local namespace can help guard against any possible collisions with 3rd party JavaScript libraries, but it need not be imperative.

like image 110
duffymo Avatar answered Sep 27 '22 17:09

duffymo


You don't need a namespace, because as you say, there is no potential naming conflict.

The only potential conflict is if you are importing a library that does not use namespaces, and it introduces a variable which conflicts with a name you placed in the script file. But if you are following the namespaces practice in all the libraries, then it doesn't matter.

like image 42
mgiuca Avatar answered Sep 27 '22 15:09

mgiuca