TIL more about destructuring
POSTED ON:
TAGS: javascript cleancode
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: javascript