Determine if a namespace/variable-name exists

Check for namespace existence in your environment variables and objects before writing to them.

Guess if "Book1.chapter22.paragraph37" exists without provoking errors and retrieve/send data if it exists with simplest JS expressions.

Call syntax:

isNS( [string], [num] );


 var nsresult =
 isNS( "Book1.chapter22.paragraph37", -1 ); 
 if( nsresult[0] ){ send( nsresult[1] ) else notify( nsresult[4], nsresult[2] ) };...

etc, etc.

Omit secondary argument (function-return modifier) to get a Boolean.
(Using 0, false, or undefined keyword has the same effect.)

 isNS( "myObject.property.subProperty.myMethod" );

_> Boolean : true/false

Modifier Possible values:
_> -1; (0|false|undefined); ( 1|true ); 2; 3 or 4.

(-1 ) _> returns array object containing complete inoculation.
( 0 ) _> optional; returns Boolean: true (if complete NS chain exist) : false (if it's broken).
( 1 ) _> if NS query exists, case true: returns the existing value; if not, case false: returns the last valid context if any, or the global object if root doesn't exist.
( 2 ) _> returns an array of existing namespaces in the argument query.
( 3 ) _> returns an array containing all specified namespaces.
( 4 ) _> returns the original query string.

*NS - stands for already familiar "Namespace" initials.
[This makes but a tinny cluster on some real A.I., Yet -a very important one!]

function isNS(arg,f) { /*b.b. Troy III p.a.e.*/
	if(typeof arg!="string") throw( 'TYPE_ERROR:"string required"');

	var i, a = arg.split("."), c = this, s = [], b, r;
	f = f || 0;
 	for( i in a ) {
		c ? a[i] in c ? ( c = c[ a[i] ], s.push( a[i] ), b = !0 ) : b = !1 : 0;
 		r = [ b, c, s, a, arg ];
 		return f < 0 ? r : r[+f||f]; 
2 Years
Discussion Span
Last Post by Troy III

( serious coders have been sufferning for this for decades. Now that it's here it seems as if they've got used to getting a painful path around, accepting the fact that it doesn't exist. )


If I understand what this function does, correctly, then surely I could just do the follwing instead? This causes no errors.

if(typeof someobject.someproperty !== "undefined") {
    // do something...
} else {
    // do something else...

echo89, what about this:

if(typeof someobject.someobj.someproperty !== "undefined") {
    // do something...
} else {
    // do something else...

what happens if someobject is undefined?


Stbuchok, I could do type of for each variable/property in nested if blocks, but that is rather tedious. I can see the use of this function now.


There are other critical uses also.

Say, checking for an explicit "undefined" value of a named property.
Checking if a variable name is already declared but (still) not initialized.
Or, that there is an object member whose value is still waiting to be assigned a value etc.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.