This content originally appeared on DEV Community and was authored by Sergey Plishka
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
This content originally appeared on DEV Community and was authored by Sergey Plishka

Sergey Plishka | Sciencx (2021-09-28T11:01:56+00:00) Using the values of a function’s arguments to default initialize subsequent arguments.. Retrieved from https://www.scien.cx/2021/09/28/using-the-values-of-a-functions-arguments-to-default-initialize-subsequent-arguments/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.