Search code examples
javascriptunicodelanguage-designlanguage-featuresreferenceerror

Why does this code throw ReferenceError: test is not defined?


var te‌st = 1
console.log(test)

Try running this simple code. It gives error: ReferenceError: test is not defined, despite the fact that I defined that variable. Why is this happening?


Solution

  • In the variable declaration, the variable name contains a zero-width non-joiner (ZWNJ) character (between e and s), which is invisible, because its width is equal to zero. However, ECMAScript specification allows this character as a part of variable name.

    However, in the console.log() call, there is just test, without any special characters. Therefore, it throws Reference Error, because the variable name is te<ZWNJ>st, not test.

    Fortunately, there's an easy way to check if a variable name contains such characters. You can paste your code into JS Bin or JS Fiddle — they denote these characters with a white dot on a red background. That's how it looks like in JS Fiddle:

    I think there are also similar features in some IDEs.

    Side note: this is an interesting way to prevent people from copy pasting the code snippets you use in answers into their own code. Consider the following code snippet:

    // Warning: non-copy-pastable, it won't work if you copy it into your code.
    function a‌dd(a, b) {
      return a + b
    }
    
    console.log(a‌dd(2, 3))

    There's a ZWNJ character in the function name and the function call, so it works here. However, if someone copied the function into their code and then manually typed console.log(add(3, 4)), it would throw ReferenceError: add is not defined.

    Please don't take the above seriously, it's rather a joke than a practical use.

    Related