Scripter Javascript Tutorial
javascriptmusiclogicscripterbookexcerpttutorial83 Name Variables For What They Are
Every time a variable is declared, that means a piece of data has some kind of important role to play in the script and should be named accordingly. This is particularly true in loops. A common loop style is the following:
// move each note up one half step
for (var i = 0; i < array.length; i++) {
var item = array[i];
.pitch += 1;
item }
The comment can become unnecessary with self-documenting code:
for ( var thisNote = 0 ; thisNotes < notes.length ; thisNote++ ) {
var note = notes[thisNote];
.pitch += HALFSTEP;
note }
In the above example, the following changes were made:
The loop variable was not clearly the index to the notes array identifying which note was being modified. By changing the loop iterator to specifically naming it a note, the context for its use is very clear.
By naming the array the plural of what it contains, the array is now clearly holding note events and not just any data.
Since the code is clearly working on a note, the call to pitch makes more sense.
A half step is a constant value in music, but a number 1 all alone could be anything, so it is handled as a
const
in code.
A comment may still be needed to explain what’s going on in the loop, especially if it’s a long loop or the code still isn’t immediately obvious. But if the comment were to be deleted for whatever reason (accidents happen!), then some of the context would have been lost in the original example. In the updated example, the code reads more naturally and no one is left having to de-code the code at a later date.