3

Looking at LWC e-bikes sample gallery, I found these comments in code regaring normalizing values. Can someone refer to what they have meant or how to do this normalization using best practices?

export default class ProductTileList extends LightningElement {
    /**
     * Whether to display the search bar.
     * TODO - normalize value because it may come as a boolean, string or otherwise.
     */
    @api searchBarIsVisible = false;

6

What they mean is javascript is loosely typed language and so for any given property you can assign any type of object like boolean, string or any other object and so it is better to have checks for the type of properties passed from parent components using typeof whenever necessary. Also note:

  1. You should always initialize the variables or else they will be undefined.
  2. Template if:true need not necessarily have boolean to render the content, it will render the content even if you assign a string value to the reactive property.

Note that you will find below function for normalising in moment.js in lwc recipes repository:

    function normalizeUnits(units) {
        return typeof units === 'string' ? aliases[units] || aliases[units.toLowerCase()] : undefined;
    }

I also created this playground link for better understanding.

Additional info:

    console.log(typeof true); // boolean
    console.log(typeof 'text'); // string
    console.log(typeof 0); // number
    console.log(typeof {}); // object
    console.log(typeof []);  // object
    console.log(typeof null);  // object
    console.log(typeof undefined);  // undefined
  • 2
    exactly what I was looking for, thank you. – Atlas Can Oct 29 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.