codegurukool.com · Free coding tutorials & online compiler

Home › JavaScript Tutorial › Classes and errors

Classes and errors

Build reusable blueprints and handle failure.

A class creates objects with shared methods. try/catch keeps one error from stopping the whole script.

Example code

<pre id="o"></pre>
<script>
  class Counter {
    constructor() { this.n = 0; }
    inc() { this.n++; return this; }
  }
  const c = new Counter().inc().inc();
  let out = "count: " + c.n;
  try { JSON.parse("{bad json"); }
  catch (err) { out += "\ncaught: " + err.name; }
  o.textContent = out;
</script>

Run this code in the online editor

← Form validationJS introduction →