In JavaScript, you can call function with or without parameters, Its not mandatory to give parameters as like Java. If you don't pass parameter values, those values will be undefined.

Using ES5

Observe below code. If parameters not defined, then default value will be assigned. But here the false values also trigger assignment
function foo(x, y) {
   x = x || 1;
   y = y || 4;
   alert(x+'  '+y);
}
foo();

Using ES6

Observe below code. The default value will be assigned if and only if the parameter value is undefined
function foo(x = 1, y = 4) {
   alert(x+'  '+y);
}
foo();
Click here to see DEMO

Using ES5 - Make Object As Option

Observe below code. We have to pass object as parameter
function selectEntries(options) {
    options = options || {}; 
    var start = options.start || 0;
    var end = options.end || -1;
    var step = options.step || 1;
    console.log(start+'  '+end+'  '+step);
}
selectEntries();

Using ES6 - Make Object As Option

You can assign default parameters for object
function selectEntries({ start=0, end=-1, step=1 } = {}) {
    console.log(start+'  '+end+'  '+step);
    alert(start+'  '+end+'  '+step);
}
selectEntries();
Click here to see DEMO

0 comments:

Blogroll

Catagories

Popular posts