Constructor() method fires when a component instance is created.
The constructor in LWC flows from parent to child which means Constructor of Parent component will get called first if you have parent child component composition.
Child Component and Controller –
childComp .html
<template>
<lightning-card title=“Child Component”>
<div class=“slds-p-left_medium slds-align_absolute-center”>
Child Component Called
</div>
</lightning-card>
</template>
childComp.js
import { LightningElement } from ‘lwc’;
export default class childComp extends LightningElement {
pChildList = [];
constructor() {
super();
window.console.log(‘::: In Child Constructor’);
}
connectedCallback() {
this.pChildList.push(‘Add Child connectedCallback’);
window.console.log(‘::: In Child connectedCallback’);
window.console.log(‘::: List values => ‘+ this.pChildList);
}
}
Parent Component and Controller –
webCompLifeCycl.html
<template>
<lightning-cardtitle=“Parent Component”>
<c-child-comp></c-child-comp><br/>
<divclass=“slds-p-left_medium”>
Page LOAD
</div>
</lightning-card>
</template>
webCompLifeCycl.js
import { LightningElement } from‘lwc’;
exportdefault class webCompLifeCycle extends LightningElement {
pList = [];
constructor() {
super();
window.console.log(‘::: In Constructor’);
}
connectedCallback() {
this.pList.push(‘Add connectedCallback’);
window.console.log(‘::: In connectedCallback’);
window.console.log(‘::: List values => ‘+this.pList);
}
}
Output –

NOTES –
- The first statement must be
super()
with no parameters. This call establishes the correct prototype chain and value forthis
. Always callsuper()
before touchingthis
. - Don’t use a
return
statement inside the constructor body, unless it is a simple early-return (return
orreturn this
). - 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.
One thought on “constructor in Lightning Web Component”