Return to Snippet

Revision: 54623
at January 5, 2012 00:15 by coprolit


Updated Code
function someFunction(params) {	
	var a = (params.a === undefined) ? "default value" : params.a /* If undefined, set default value */,
	b = (params.b === undefined) ? "default value" : params.b /* If undefined, set default value */,
	sum = a + b,
	myobject = {},
	i,
	j,
	el = (params.el === undefined) ? document.getElementById("default") : params.el /* If undefined, set default value */,
	style = el.style;
	// do something with el and style... 
   
	// function body...
}

// call function with associative array:
someFunction({ 
	a: 'Dette er en titel',
	b: 'http://www.dr.dk/OmDR/Nyt_fra_DR/Nyt_fra_DR/2008/11/25141639.htm',
	el: document.getElementById("result")
})

Revision: 54622
at January 5, 2012 00:13 by coprolit


Initial Code
function someFunction(params) {	
	var a = (params.a === undefined) ? "default value" : params.a /* If undefined, set default value */,
		b = (params.b === undefined) ? "default value" : params.b /* If undefined, set default value */,
		sum = a + b,
		myobject = {},
		i,
		j,
		el = (params.el === undefined) ? document.getElementById("default") : params.el /* If undefined, set default value */,
		el = params.el,
		style = el.style;
	// do something with el and style... 
   
	// function body...
}

// call function with associative array:
someFunction({ 
	a: 'Dette er en titel',
	b: 'http://www.dr.dk/OmDR/Nyt_fra_DR/Nyt_fra_DR/2008/11/25141639.htm',
	el: document.getElementById("result")
})

Initial URL

                                

Initial Description
By not being limited to provide certain arguments/parameters in right order when calling a function, makes the function more versatile and easier to extend without breaking old code (e.g. calls to the function). 
One solution is to pass an associative array holding the parameters. 
Advantage: argument order is unnecessary, each argument have a label - easier to remember.

Initial Title
Optional function arguments/parameters by using associative array

Initial Tags
object, number, array, function

Initial Language
JavaScript