by Sai gowtham

How to add Default function parameters in JavaScript

Default function parameters help us to initialize the parameters with a default values.

If we don’t pass any value to a function parameters, it will be initialized with a value undefined.

Let’s see examples.

Without default parameters

function enterYourname(name){
    return 'User name is '+ name
}

console.log(enterYourname())

In the above example, we don’t pass any argument value to the function parameter name so that it will return username is undefined.

default parameters JavaScript

With default parameters

function enterYourname(name="Unknown"){
    return 'User name is '+ name
}

console.log(enterYourname());

Here we added a default value to Unknown.

default function parameters JavaScript

More examples with default parameters

function add(a,b=5){
    return a+b;
}

console.log(add(1))

// output -> 6
function combineArrays(a,b=[5,6,7]){
    return [...a,...b];
}

console.log(combineArrays([1,2,3,4]))

// output [1,2,3,4,5,6,7]

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course