# Run Code When a Component Is Created

The `constructor()` method fires when a component instance is created. Don’t add attributes to the host element during construction. You can add attributes to the host element in any other lifecycle hook.

The constructor flows from parent to child, which means that it fires in the parent first. You can't access child elements because they don't exist yet. Properties aren’t passed yet, either. Properties are assigned to the component after construction and before the [`connectedCallback()` hook](/docs/platform/lwc/guide/create-lifecycle-hooks-dom.md).

## Constructor Considerations

These requirements from the [HTML: Custom elements spec](https://html.spec.whatwg.org/multipage/custom-elements.html#custom-element-conformance) apply to the `constructor()`.

- The first statement must be `super()` with no parameters. This call establishes the correct prototype chain and value for `this`. Always call `super()` before touching `this`.
- Don’t use a `return` statement inside the constructor body, unless it is a simple early-return (`return` or `return this`).
- Don’t use the `document.write()` or `document.open()` methods.
- Don’t inspect the element's attributes and children, because they don’t exist yet.
- Don’t inspect the element’s public properties, because they’re set after the component is created.

## Don’t Add Attributes to Host Element During Construction

You can add attributes to the host element during any stage of the component lifecycle other than construction.

This pattern isn't recommended, because it adds an attribute to the host element in the `constructor()`.

```javascript
// don't do this
import { LightningElement } from "lwc";
export default class Deprecated extends LightningElement {
  constructor() {
    super();
    this.classList.add("new-class");
  }
}
```

To add an attribute to the host element, use the `connectedCallback()` method instead.

```javascript
import { LightningElement } from "lwc";

export default class New extends LightningElement {
  connectedCallback() {
    this.classList.add("new-class");
  }
}
```

**See Also**

- [Lifecycle Flow](/docs/platform/lwc/guide/create-lifecycle-hooks.md)
