4
Is it possible to make parameter presets in Javascript functions? Something like:
function teste(oi = "ola", type = 1) {
To predefine variables if they are not defined?
4
Is it possible to make parameter presets in Javascript functions? Something like:
function teste(oi = "ola", type = 1) {
To predefine variables if they are not defined?
4
This is usually called default Parameters. And Javascript does not allow this syntax. The best that can be done is to set values early in the function:
function teste(oi, type) {
oi = (typeof(oi) === "undefined" || oi === null) ? "ola" : oi;
type = (typeof(type) === "undefined" || oi === null) ? 1 : type;
//continua a função aqui
}
I put in the Github for future reference.
If you are going to use this a lot it is possible to create a function to simplify this syntax. Something like this:
function def(variable, value) {
return (typeof(variable) === "undefined" || === null) ? value : variable;
}
Then I’d wear it like this:
function teste(oi, type) {
oi = def(oi, "ola");
type = def(type, 1);
//continua a função aqui
There is an experimental way to have a syntax in the conforming language MDN documentation. This way could use the way you want. At the moment only works in Firefox.
4
There are several ways to do this, one of them is the following:
function foo(a, b)
{
a = typeof a !== 'undefined' ? a : 'seu_valor_default_a';
b = typeof b !== 'undefined' ? b : 'seu_valor_default_b';
//Seu código
}
OBS.: Response copied from the original made by Tom Ritter in: https://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function
Browser other questions tagged javascript function parameters
You are not signed in. Login or sign up in order to post.
In addition to the question at the top, see also http://answall.com/questions/48548/%C3%89-poss%C3%Advel-nominate-a-par%C3%A2metro-no-momento-da-chamada-da-fun%C3%A7%C3%A3o
– bfavaretto
On this other issue, have a function
WithDefaults
that given another function F and an array A, generates another function F' that accepts default parameters. jsfiddle– Miguel Angelo