2
\$\begingroup\$

After finishing this article : Lessons From A Review Of JavaScript Code

I was wondering if my namespace

/**
 * The primary namespace object
 * @type {Object}
 * @alias BDDS
 */
if(!window['BDDS']) {
    window['BDDS'] = {};
}

if attached to the window, is this snippet invalid, according to the following?

Problem 9

Problem: The namespacing pattern used is technically invalid.

Feedback: While namespacing is implemented correctly across the rest of the application, the initial check for namespace existence is invalid. Here’s what you currently have: 1 if ( !MyNamespace ) { 2
MyNamespace = { }; 3 }

The problem is that !MyNamespace will throw a ReferenceError, because the MyNamespace variable was never declared. A better pattern would take advantage of boolean conversion with an inner variable declaration, as follows: 01 if ( !MyNamespace ) { 02 var MyNamespace = { }; 03 } 04 05 //or 06 var myNamespace = myNamespace || {}; 07 08 // Although a more efficient way of doing this is: 09 // myNamespace || ( myNamespace = {} ); 10 // jsPerf test: http://jsperf.com/conditional-assignment 11 12 //or 13 if ( typeof MyNamespace == ’undefined’ ) { 14 var MyNamespace = { }; 15 }

This could, of course, be done in numerous other ways. If you’re interested in reading about more namespacing patterns (as well as some ideas on namespace extension), I recently wrote “Essential JavaScript Namespacing Patterns.” Juriy Zaytsev also has a pretty comprehensive post on namespacing patterns.

\$\endgroup\$
1
  • \$\begingroup\$ It won't throw a reference error, if that's what you mean. \$\endgroup\$ Commented Oct 28, 2011 at 15:19

2 Answers 2

3
\$\begingroup\$

No your code is correct.

!reference only throws a reference error if its not defined.

window is defined and window["not_defined"] just returns undefined for not defined variables.

\$\endgroup\$
0
\$\begingroup\$

I prefer a one liner but it's just a syntax thing:

window.SomeNamespace = SomeNamespace || {};
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.