Scope of defined variables

0 votes
asked Apr 16, 2015 by chris-m-8014 (760 points)
Can I have a variable in a mapping function, say, myVariableName, and have the same name defined as a channel cache variable, or a system variable, or even a global variable?

If the same name can be defined at multiple levels, do they take precedence when used?

1 Answer

+1 vote
Best answer

Very good question about scope.  For those that don't know, scope is the context a variable can be used.  

Each mapping function is wrapped in its own JavaScript function.  This means that any variable declared in the mapping function can be used only within the context or scope of the function.  Feel free to reuse the name in a different mapping function~ it will be a new variable.

There are some declared and initialized JavaScript variables which are included in the scope of QIE scripts.  These would be the QIE specific objects found in the Code Wizard like messageCache, channelCache, source, message, qie, StringUtils, etc. The key names in the caches do not effect variables with the same name.

// myValue is a local variable and is not related to messageCache values.

// these are two separate variables and values.

var myValue = 'blue';

messageCache.setValue('myValue', 'red'); 

QIE System Variables are accessed with qie.setVariable() and qie.getVariable().  Although System Variables cannot have duplicate names, you may name any local variable or cache name the same. QIE System Variables can be in a specific zone or be in the global zone, but they will have the same behavior.

// No variable conflict

var myValue = 'Some value';

var otherValue = qie.getVariable('myValue');

QIE uses JavaScript, so it will follow the scope defined by the Javascript standards. (See for some examples). A global JavaScript variable will actually pass out of scope when the mapping node completes.  However, you should use messageCache.setValue() and messageCache.getValue() to persist and retrieve a value from one mapping function to the next.

answered Apr 16, 2015 by mike-r-7535 (13,830 points)
selected Apr 16, 2015 by chris-m-8014
commented Apr 16, 2015 by rich-c-2789 (17,430 points)
Just remember to use "var" to define your variables.  If "var" is left off it has global scope making it accessible within any mapping function within the mapping node.