Better functions with default parameters (javascript)
image author: https://www.google.com/imgres?imgurl=https%3A%2F%2Fres.cloudinary.com%2Fpracticaldev%2Fimage%2Ffetch%2Fs--_aWlnjbL--%2Fc_imagga_scale%2Cf_auto%2Cfl_progressive%2Ch_420%2Cq_auto%2Cw_1000%2Fhttps%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2

Better functions with default parameters (javascript)

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


Alfredo Martínez García

Software Engineer || Front End Developer at Phase2Technology

4 年

Thank you for Sharing bro!!

Vaibhav Mavani

Full Stack Developer | ReactJS, Redux, Node.js, Django

4 年

Thanks for sharing

要查看或添加评论,请登录

社区洞察