class keyword is not working in Khan Academy editor

68 views Asked by At

This code throws the error "Unexpected reserved word" in the Khan Academy html editor. I am quite sure that this is a problem with Khan Academy's editor and not my code, but how do I fix it?

<html lang="en"> 
<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script>
        class Example {
            constructor () {
                
            }
        }
    </script>
</body>
</html>
1

There are 1 answers

0
bhavjitChauhan On BEST ANSWER

Khan Academy's webpage environment uses a custom version of Slowparse to lint the HTML code before running it. This Slowparse in turn uses a version of Esprima nearly a decade out-of-date to parse any JavaScript code. As a result, the environment cannot parse classes which were only introduced in ECMAScript 2015.

You can work around this limitation by exploiting the incomplete set of valid script type attributes recognized by Khan. Using any valid value other than no value (<script>) and text/javascript will circumvent the linting (and transformation) of the JavaScript code.

For example, using module with your code:

<script type="module">
    class Example {
        // ...
    }
</script>

The caveat here is that working with globals is not straightforward. Using the application/javascript media type with your code, for example, will silently fail (errors only logged to the browser console) because of a syntax error after the first run. This is because Khan doesn't properly clean the environment between runs. You have three options to deal with this:

  • use JavaScript modules keeping in mind the differences to standard scripts (one of them conveniently being variables not global scoped by default)
  • use a JavaScript media type unrecognized by Khan and write your code in a block scope (e.g. an IIFE)
  • exclusively use the var keyword or no keyword to "declare" variables