JavaScript and Max: Some Basic Examples

Getting our feet wet

Following on our strategy for some other topics, let's dive right into a set of three small examples on Javascript and Max. Each example consists of two files, a max patch file, and a javascript file. The interaction with these patches should feel straight forward, and peeking at the javascript files will explain how it really works. If it looks too much, don't worry. Feel free to move on to lessons 3 to 5 and come back later to re-learn from these examples.

Bang twice

Start with downloading these two files by right-clicking the links, and then selecting "Save Link As...". Make sure to save them on the same folder.

Then open the patch file to try it out. Everytime you push the button, or the message box foo, a bang should be printed to the max console. Do make sure you also have the console window open, so you can confirm this. The core element in this patch is the js object which is loading the javascript file. Shall you double click this object, a Max text editor window will open. You can also define this action to open the javascript file with your favorite text editor, such as one of the ones listed in the resources page, by changing the settings under Preferences > All > Interface. As you already know, in javascript everything after a double slash, until the end of the line, will not be executed. The portion of actual executable code here is very small, all the rest is documenting it. Take a look at it.


Same number once

Start by downloading these two files and saving them on the same folder.

This patch is very similar to the previous one. It receives a value, and it outputs it, though here it is not printing to the Max console. When you'll open the javascript code you'll notice that there is much more executable code. Also different here is the fact that we are now expecting to receive floats or ints and we took some time to do some error handling. This example introduces a practice while writing javascript code that you should take into consideration when you'll start writing your own code.


Number array

Once again, start by downloading these two files and saving them on the same folder.

Though it contains a patch whose interface still resembles the previous examples, this one will introduce the use of an array in Javascript for Max, together with some new ways to store and process data. Take a look at the commented javascript code.