Pilcrow Records

Scripter Javascript Tutorial

javascriptmusiclogicscripterbookexcerpttutorial

83 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];
	item.pitch += 1;
}

The comment can become unnecessary with self-documenting code:

for ( var thisNote = 0 ; thisNotes < notes.length ; thisNote++ ) {
	var note = notes[thisNote];
	note.pitch += HALFSTEP;
}

In the above example, the following changes were made:

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.