stackdave stackdave - 6 days ago 6
Javascript Question

javascript , omit parameters in functions , does not affect the function

I've seen a lot functions in javascript that have 3 parameters , by example second parameter it's a value, and third a function, and when you omit the second parameter , and send the third parameter ( function) like second parameter; there is no error. how it does work ?
There are scenarios where second and third parameter are functions and do it that ? What is the architecture behind this?

Examples:

full 3 parameters :

client.query('SELECT $1::int AS number', ['1'], function(err, result) {


2 parameters:

client.query('SELECT * from accounts', function(err, result)


3 parameters with null in second parameter:

client.query('SELECT * from accounts', null, function(err, result)

Answer

Before ES2015 there was this way:

function foo(param1, param2, param3){
    if(!param2){
        param2 = standard_value;
    }
    if(!param3){
        param3 = standard_value;
    }
    if(typeof param2 === "function"){
        param3 = param2;
    }
    // do stuff
}

With ES2015 you can use this:

function foo(param1, param2 = standard_value, param3 = standard_value){
    if(typeof param2 === "function"){
        param3 = param2;
    }
    // do stuff
}
Comments