Variable scope and naming
JavaScript is a relatively informal language and does not require you to define variables before assigning values to them. Neither does it enforce strict type checking, or signal when a variable is redefined. This makes JavaScript fast and easy to work with, but can quickly lead to illegible code and confounding errors, especially since you can create variables that overwrite built-in ones.
One bug that can defy debugging is when you declare a variable with the same name as a built-in one, like work, conn and current, so you will need to familiarize yourself with the reserved names used by IBM® Security Directory Integrator.
Another common problem occurs when you create new variables that redefine existing ones, perhaps used in included Configs or Script Libraries. These mistakes can be avoided if you are conscious about the naming of variables and their scope. Scope defines the sphere of influence of a variable, and in IBM Security Directory Integrator we talk about global variables; those which are available in all Hooks, Script Components and attribute maps, and those that are local to a function.
myVar = "Know thyself";
This
variable will be available from this point on for the life the AL.
Making this variable local requires two steps: using the var keyword
when declaring the variable, and putting the declaration inside a
function: function myFunc() {
var myVar = "Know thyself";
}
Now myVar as defined above will cease
to exist after the closing curly brace. Note that placing the variable
inside a function is not enough; you have to use var as
well to indicate that you are declaring a new, local, variable. var glbVar = "This variable has global scope";
glbVar2 = "Another global variable";
function myFunc() {
var lclVar = "Locally scoped within this block";
glbVar3 = "This is global, since "var" was not used";
};
As long as you declare a local variable within a function
then you can call it what you like. As soon as it goes out of scope,
any previous type and value are restoredEven though the var keyword is not required for defining global variables, it is best practice to do so. And it is recommended that you define your variables at the top of your script, including enough comments to give the reader an understanding of what they will be used for. This approach not only improves the legibility of your code, it also forces you to make conscious decisions about variable naming and scope.1