If you pass one or more parameters, how will handle them ?. In ES5 arguments virtual array will be there, You need to process that array

Using ES5

Observe below code. Here we are processing arguments array.  
function logAllArguments() {
    for (var i=0; i < arguments.length; i++) {
        console.log(arguments[i]);
    }
}
logAllArguments('arg 1', 'arg 2', 'arg 3');
Click here to see DEMO
Below code is for handling rest of the parameters. In below code first parameter is mandatory, rest of the parameters extracted from arguments array
function logAllArguments() {
    var pattern = arguments[0];
    var args = [].slice.call(arguments, 1);
    for (var i=0; i < args.length; i++) {
        console.log(args[i]);
    }
}
logAllArguments('arg 1', 'arg 2', 'arg 3');

Using ES6

Observe below code. Here we are handling arguments with spread operator
function logAllArguments(...args) {
    for (const arg of args) {
        console.log(arg);
    }
}
logAllArguments('arg 1', 'arg 2', 'arg 3');
Click here to see DEMO
To handle rest of the parameters we can use rest of the parameters
function logAllArguments(arg1, ...args) {
    console.log(arg1);
    for (const arg of args) {
        console.log(arg);
    }
}
logAllArguments('arg 1', 'arg 2', 'arg 3');
Click here to see DEMO

0 comments:

Blogroll

Catagories

Popular posts