Hi Mahesh and thanks for your interesting article.
We can also use the de-structuring when dealing with event listener's callback variables for instance.
constmyInput=document.getElementById("myInput");if(null!==myInput){myInput.addEventListener("input",event=>{console.log(`input value: ${event.target.value}.`);console.log(`input value uppercased: ${event.target.value.toUpperCase()}.`);console.log(`input value lowercased: ${event.target.value.toLowerCase()}.`);});}
Here, I'm using three times the value from my input. We can shorten it by using the de-structuring in the callback variable directly.
constmyInput=document.getElementById("myInput");if(null!==myInput){myInput.addEventListener("input",({target})=>{console.log(`input value: ${target.value}.`);console.log(`input value uppercased: ${target.value.toUpperCase()}.`);console.log(`input value lowercased: ${target.value.toLowerCase()}.`);});}
We can even go further by nesting the de-structuring.
constmyInput=document.getElementById("myInput");if(null!==myInput){myInput.addEventListener("input",({target:{value}})=>{console.log(`input value: ${value}.`);console.log(`input value uppercased: ${value.toUpperCase()}.`);console.log(`input value lowercased: ${value.toLowerCase()}.`);});}
Pretty cool to shorten the syntax and remove some repetitions in the code. Though it would be interesting to provide a real-world example.
Hi Mahesh and thanks for your interesting article.
We can also use the de-structuring when dealing with event listener's callback variables for instance.
Here, I'm using three times the value from my input. We can shorten it by using the de-structuring in the callback variable directly.
We can even go further by nesting the de-structuring.
Pretty cool to shorten the syntax and remove some repetitions in the code. Though it would be interesting to provide a real-world example.
myInput?.addEventListener allows to get read of the if statement.
Always good to keep your code as close to the left as possible.