LWC Best Practices & Considerations

167 Views

Hi again! This blog post is going to be a different one as I’ll keep updating this post with all the latest findings.

In this blog post I am going to share all the best practices and considerations regarding LWC for not just by the Salesforce but even with personal experience.

First, let’s start with FOR LOOP,

FOR LOOP

JS ES6 bring different kind of FOR LOOPS (click here to have a look in details) but in LWC – make sure to use the one which doesn’t conflict with lwc architecture.

For example, if you’re going to use forEach,

this.lstAccounts.forEach(function(acc){
    console.log(acc.Name);
});

You won’t be able to access THIS.VARIABLE inside this loop. Here is a demonstration,

this.lstAccounts.forEach(function(acc){
    console.log(acc.Name);
    console.log(this.someBooleanval); //THIS VALUE WILL BE NULL
});

The reason is that such kind of loop also uses THIS. and looks for the value inside a loop where such variable is not assigned hence – NULL.

SO what should you do ? Use another kind of FOR LOOP – like:

for(let acc of this.lstAccounts){
    console.log(acc.Name);
   console.log(this.someBooleanval); //VALUE WILL BE ACCESSIBLE HERE
}

I hope this will help you at some point – I’ll keep updating this post with latest updates.

Happy Coding!

Leave a Comment