Today I Learned - Rocky Kev

TIL more about destructuring

POSTED ON:

TAGS:

Destructuring allows us to extract values from arrays and objects and store them in variables with a more convenient syntax.

For example --

const tasks = ['make coffee', 'walk dog', 'go shopping'];

export const [task1, task2, task3] = tasks

// task1 == 'make coffee'
// task2 == 'walk dog'
// task3 == 'go shopping'

The way you may have seen it is like this:


function welcome (props) {
return `hello, ${props.name}`;
}

function welcome ({name}) {
return `hello, ${name}`;
}

The sweeter version that I've seen is:


const apiData = {
name: 'rocky',
favoriteMovie: 'Independence Day',
country: 'US',
links: {
social: {
twitter: '@rockykev',
},
websites: {
main: 'heyitsrocky.com',
til: 'til.heyitsrocky.com'
}
}
}

const { mainWebsite, tilWebsite } = apiData.links.websites;

Renaming Variables:

We can rename variables when destructuring using “:” and assign a new name.


const shape = { w: 800, h: 400 };

// rename
const { w: width, h: height } = shape;

// width = 800
// height = 400

REFERENCE:
Must know JavaScript for react developers


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.