JavaScript Reference

Quick Reference

The try…catch…finally statement handles errors without stopping JavaScript to output the error.

The try statement defines the code block to run, while the catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result.

<!-- html element to place output -->
<p id="my_output"></p>

In the following, we use x as our value (let’s say it was input by the user in a form field). The user was asked to input a number between 1 and 5.

We then use the throw statement to look for errors (try) and output them (catch) to the html element.

If no errors are found, nothing will be output using the “catch”, and the code will continue to run after line 13.

// variable
let x = 13;

// try catch finnally statement
try {
    if(x == '')  throw 'You did not enter a value.';
    if(isNaN(x)) throw 'You did not enter a number.';
    if(x > 5)   throw 'The number entered is too high.';
    if(x < 1)  throw 'The number entered is too low.';
  }
catch(error) {
    document.getElementById('my_output').innerHTML = error;
  }
finally {
    alert('Don\'t forget to visit our tutorials!');
  }

Output

The number entered is too high.

Don't forget to visit our tutorials! (alert)

Syntax

try {
    tryCode - code to be executed
}
catch(err) {
    catchCode - code to handle errors
}
finally {
    finallyCode - code to be executed regardless of the try result
}

JavaScript Notes:

  • When using JavaScript, single or double quotation marks are acceptable and work identically to one another; choose whichever you prefer, and stay consistent
  • JavaScript is a case-sensitive language; firstName is NOT the same as firstname
  • Arrays count starting from zero NOT one; so item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on
  • JavaScript variables must begin with a letter, $, or _
  • JavaScript variables are case sensitive (x is not the same as X)

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.