Created
December 11, 2021 21:59
-
-
Save joeywhelan/cc772dba25d155d4cb705dbc678c1333 to your computer and use it in GitHub Desktop.
Javascript Function Argument Options and Object Conditionals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @fileoverview Various function argument and object constructor examples | |
* @author Joey Whelan | |
*/ | |
//base example | |
function example1(p1,p2,p3) { | |
console.log('example1'); | |
const params = { | |
"p1": p1, | |
"p2": p2, | |
"p3": p3 | |
}; | |
console.log(params); | |
}; | |
example1('a', 'b', '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'); | |
//argument with default val | |
function example3(p1,p2,p3='c') { | |
console.log('\nexample3') | |
const params = { | |
"p1": p1, | |
"p2": p2, | |
"p3": p3 | |
}; | |
console.log(params); | |
}; | |
example3('a', 'b'); | |
//arguments passed an 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'}); | |
//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"}); | |
//destructured arguments, undefined arg | |
function example6({ p1,p2,p3 }) { | |
console.log('\nexample6'); | |
const params = { | |
"p1": p1, | |
"p2": p2, | |
"p3": p3 | |
}; | |
console.log(params); | |
}; | |
example6({"p1": "a", "p2": "b"}); | |
//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"}); | |
//destructured arguments, default val | |
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"}); | |
//argument spread operator for variadic func | |
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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment