How to use the JavaScript console

The code editor helps you to find syntax errors. If something isn’t quite right, the editor will give you a hint by underlining the critical part in red. Just hover over the red underline and a popup window with a hint will appear.

However, sometimes you need a console to log messages to it, or to see error messages which occur at runtime. For example, an uncaught runtime error stops the execution of the script and you may want to find out what happened. A JavaScript console can help you with that.

You can use your browser’s built-in JavaScript developer console for that purpose. In Google Chrome, you can open the console by pressing Cmd + Opt + J (Mac) or Ctrl + Shift + J (Windows / Linux). Alternatively, go to the Chrome menu, select More Tools > Developer Tools and open the Console tab. Most modern browsers have similar tools and a possibility to access the JavaScript console.

Once you’ve opened the console, you will see a lot of stuff in there. You can ignore most of it. You are just interested in the Errors and Logs.

There are many app related messages you don’t need and you can filter them out by unchecking them in the console settings.

You can also always clear the console by clicking on the “Clear” button.

Keep in mind that the layout and design of the DevTools changes from time to time. The version in your browser might look a little different but the functionality should still be the same.

Now, in the CoSpaces code editor, you can use Space.log() to log a message to the console.

for(let i = 0; i < 10; i++) {
  Space.log(i);
}

When you run the script by pressing the “Play” button, the messages will appear in the console.

If you run into an uncaught error, the execution of the script will stop and the related error message will be displayed.

function sum(a, b) {
  return a + b;
}

let x = sub(2, 3);

In the example above, we try to call the sub() function, which is not defined. Now that we know the error, we can easily fix it.

Feel free to use JavaScript’s try, catch, finally and throw statements to catch errors and/or throw custom errors.

let n = -1;

try {
  if(n < 0) {
    throw 'is negative.';
  }
} catch(error) {
  Space.log('Number ' + error);
} finally {
  n = 0;
}

Space.log(n);

To avoid tedious debugging sessions, we recommend that while you’re coding, just run your script after every other logical change. Check if it runs and have a look at the console output.

1 Like