Skip to main content Accessibility Feedback

Setting default arguments with JavaScript arrow functions

Yesterday, we looked at how to set default values for JavaScript function arguments.

With arrow functions, it’s even easier.

You can set a default value for each argument at the time that you give it a name with = value.

// Setting defaults with a traditional function
var add = function (num1, num2) {

    // If num1 or num2 aren't defined, set them to 0
    num1 = num1 || 0; // conditional operator
    num2 = num2 ? num2 : 0; // ternary operator

    // Add the numbers
    return num1 + num2;

};

// Setting defaults with an arrow function
var add = (num1 = 0, num2 = 0) => num1 + num2;

Arrow functions aren’t production-ready at the moment—they require a compiler to have good enough browser compatibility—but this is still a great feature.

If you like this post, you might also enjoy my vanilla JS pocket guide on variables, functions, and scope.


🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips