DEV Community

Discussion on: You may not know destructuring yet

Collapse
 
aminnairi profile image
Amin • Edited

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.

const myInput = 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()}.`);
    });
}
Enter fullscreen mode Exit fullscreen mode

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.

const myInput = 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()}.`);
    });
}
Enter fullscreen mode Exit fullscreen mode

We can even go further by nesting the de-structuring.

const myInput = 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()}.`);
    });
}
Enter fullscreen mode Exit fullscreen mode

Pretty cool to shorten the syntax and remove some repetitions in the code. Though it would be interesting to provide a real-world example.

Collapse
 
xavierbrinonecs profile image
Xavier Brinon

myInput?.addEventListener allows to get read of the if statement.
Always good to keep your code as close to the left as possible.