September 28, 2021 11:01 am GMT
Original Link: https://dev.to/russelldev/using-the-values-of-a-function-s-arguments-to-default-initialize-subsequent-arguments-51bn
Using the values of a function's arguments to default initialize subsequent arguments.
You knew that when coding in javascript, you can use the values of a function's arguments to default initialize subsequent arguments.
const rectangle = (width, height, square = width * height) => { console.log({ width, height, square });};rectangle(5, 5, 25); // {width: 5, height: 5, square: 25}rectangle(3, 7); // {width: 3, height: 7, square: 21}
But not vise versa, compiler going through arguments and create variables that can be used for initializing next ones.
const square = (square = length * length, length) => { console.log({ length, square });};square(7); // {length: undefined, square: 7}
You can also use object deconstructing. But initializing parameters must come before initialized ones.
const figure = ({ w, h } = {}, { width = w, height = h } = {}, square = width * height) => { console.log({ width, height, square });};figure(undefined, { width: 3, height: 7 }); //{width: 3, height: 7, square: 21}figure({ w: 5, h: 8}); //{width: 5, height: 8, square: 40}
You can event use function calls and pass previous arguments to them.
const perimeter = (...sides) => sides.reduce((p, side) => p + side);const trapezium = (a, b, c, d, p = perimeter(a, b, c, d)) => { console.log(`Perimeter - ${p}`);};trapezium(12, 36, 15, 15); //Perimeter - 78
Original Link: https://dev.to/russelldev/using-the-values-of-a-function-s-arguments-to-default-initialize-subsequent-arguments-51bn
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To