Categories
JavaScript Answers

How to Fix the ‘SyntaxError: Unexpected “#” used outside of class body’ Error in Our JavaScript App?

Spread the love

Sometimes, we may run into the ‘SyntaxError: Unexpected "#" used outside of class body’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘SyntaxError: Unexpected "#" used outside of class body’ when we’re developing JavaScript apps.

Fix the ‘SyntaxError: Unexpected "#" used outside of class body’ When Developing JavaScript Apps

To fix the ‘SyntaxError: Unexpected "#" used outside of class body’ when we’re developing JavaScript apps, we should make sure that we only use the # in places where they’re valid.

For instance, instead of writing code like:

document.querySelector(#foo)

where the # sign isn’t expected to be in front of a variable name, we should write:

document.querySelector("#foo")

where the # sign is in a string.

# is valid inside a string so the error won’t be thrown.

Also, if we’re using the # sign to declare a class with a private field, we should make sure we only access the private field where it is available.

For instance, instead of writing:

class ClassWithPrivateField {
  #privateField

  constructor() {
  }
}

this.#privateField = 2

where we’re trying to access privateField outside a class, which triggers the error, we should instead write:

class ClassWithPrivateField {
  #privateField

  constructor() {
    this.#privateField = 2
  }
}

Conclusion

To fix the ‘SyntaxError: Unexpected "#" used outside of class body’ when we’re developing JavaScript apps, we should make sure that we only use the # in places where they’re valid.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *