top of page

Use Safe Navigation Operator (?.) in Lightning Web Components

Sometimes in lwc we get these nasty errors.


These errors occurs when we try to query a class and try to fetch value or other attribute. such as


let fName = this.template.querySelector("fname").value;

Here if "fname" class is wrong or not available at the moment, it will throw above error. So to tackle this issue we can use same navigation operator in Javascript.


let fName = this.template.querySelector("fname")?.value;

Here we have used save navigation operator and now, if "fname" class is invalid, then fName variable will be assigned as undefined and if "fname" class is valid, then valid value will be assigned. in any case above statement will not throw any UI error.


We can use safe navigation operator inside if condition or at rvalue, but safe navigation operator cannot be used at lvalue.

1,074 views0 comments

Comments


bottom of page