Better functions with default parameters (javascript)
Bernardo Aguayo Ortega
Senior Software Engineer @ Ubidots | React & Next.js Specialist | Building Scalable Web Applications with JavaScript, TypeScript, and Node.js
Imagine the you have a function
function convertTemperature(celsius , decimalPlaces) { const fahrenheit = celsius * 1.8 + 32; return Number(fahrenheit.toFixed(decimalPlaces)); }
so that is a function that allow us to convert celsius to fahrenheit and handle de decimals of the result.
But what happen if you forget to put the decimal places values, our function will break, how can we avoid that kind of issues? the answer is simple, use default parameters:
function convertTemperature(celsius , decimalPlaces = 1) { const fahrenheit = celsius * 1.8 + 32; return Number(fahrenheit.toFixed(decimalPlaces)); }
What changed from the function above? when you defined the parameters you only have to add a default parameter with the "=" symbol and next to the value of the default parameter, example:
function anyfunction(param1 = defaultvalue){...}
if you read that, I hope to be of help to you <3
Software Engineer || Front End Developer at Phase2Technology
4 年Thank you for Sharing bro!!
Full Stack Developer | ReactJS, Redux, Node.js, Django
4 年Thanks for sharing