Pilcrow Records

Scripter Javascript Tutorial

javascriptmusiclogicscripterbookexcerpttutorial

84 Keep Variables Unique

JavaScript’s ability to have a variable contain any kind of data at any point is a double-edged sword. Not having to declare a data type when declaring the variable is a nice convenience, but the purpose of the variable can be made unclear.

var rootNote = 60;
for ( var thisNote = 0 ; thisNotes < chord.length ; thisNote++ ) {
	var note = chord[thisNote];
	if ( note.pitch == rootNote ) {
		rootNote = note;
	}
}

In the above example, the variable rootNote is used to store both the target pitch and the note which matches that pitch. However, if the target pitch isn’t found in the chord, then rootNote is still 60 and not an actual note object, which the subsequent code may assume to be true. To fix this, use two variables: one for the target pitch and one for the captured note.

var targetPitch = 60;
var rootNote;
for ( var thisNote = 0 ; thisNotes < chord.length ; thisNote++ ) {
	var note = chord[thisNote];
	if ( note.pitch == targetPitch ) {
		rootNote = note;
	}
}

Then, any code which follows can check to see if rootNote actually has a value, as opposed to carrying over 60 which is a value, but is not the correct type:

if ( rootNote != undefined ) {
	// do something with rootNote
}