Saturday, December 11, 2021

Javascript Function Argument Options and Object Conditionals

Summary

This post is purely some code examples of different ways to structure arguments to functions.  I show some examples of conditional object properties as well.

Base

function example1(p1,p2,p3) {
    console.log('example1');

    const params = {
        "p1": p1,
        "p2": p2,
        "p3": p3
    };
    console.log(params);
};
example1('a', 'b', 'c');
example1
{ p1: 'a', p2: 'b', p3: 'c' }


Insufficient Number of Arguments

function example2(p1,p2,p3) {
    console.log('\nexample2')
    const params = {
        "p1": p1,
        "p2": p2,
        "p3": p3
    };
    console.log(params);   
};
example2('a', 'b');
example2
{ p1: 'a', p2: 'b', p3: undefined }


Argument with a default value

function example3(p1,p2,p3='c') {
    console.log('\nexample3')
    const params = {
        "p1": p1,
        "p2": p2,
        "p3": p3
    };
    console.log(params);
};
example3('a', 'b');
example3
{ p1: 'a', p2: 'b', p3: 'c' }


Arguments passed as an object

function example4(allparms) {
    console.log('\nexample4')
    const params = {
        "p1": allparms.p1,
        "p2": allparms.p2,
        "p3": allparms.p3
    };
    console.log(params); 
}
example4({"p1": 'a', "p2": 'b', "p3": 'c'});
example4
{ p1: 'a', p2: 'b', p3: 'c' }


Argument object destructured

function example5({ p1,p2,p3 }) {
    console.log('\nexample5');

    const params = {
        "p1": p1,
        "p2": p2,
        "p3": p3
    };
    console.log(params);
};
example5({"p1": "a", "p2": "b", "p3": "c"});
example5
{ p1: 'a', p2: 'b', p3: 'c' }


Destructured arguments, undefined argument

function example6({ p1,p2,p3 }) {
    console.log('\nexample6');

    const params = {
        "p1": p1,
        "p2": p2,
        "p3": p3
    };
    console.log(params);
};
example6({"p1": "a", "p2": "b"});
example6
{ p1: 'a', p2: 'b', p3: undefined }


Destructured arguments, undefined arg, conditional object property

function example7({ p1,p2,p3 }) {
    console.log('\nexample7');

    const params = {
        "p1": p1,
        "p2": p2,
        ...(p3 && {"p3": p3})
    };
    console.log(params);
};
example7({"p1": "a", "p2": "b"});
example7
{ p1: 'a', p2: 'b' }


Destructured arguments, default value

function example8({ p1,p2,p3='c' }) {
    console.log('\nexample8');

    const params = {
        "p1": p1,
        "p2": p2,
        ...(p3 && {"p3": p3})
    };
    console.log(params)
};
example8({"p1": "a", "p2": "b"});
example8
{ p1: 'a', p2: 'b', p3: 'c' }


Variadic function, spread operator

function example9(...allParms) {
    console.log('\nexample9');

    let params = {};
    let ind = 1;
    for (let parm of allParms) {
        params[`p${ind++}`] = parm;
    };

    console.log(params);
};
example9("a", "b", "c");
example9
{ p1: 'a', p2: 'b', p3: 'c' }


Gist


Copyright ©1993-2024 Joey E Whelan, All rights reserved.