Preset in Javascript function parameters

Asked

Viewed 99 times

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?

  • 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

  • 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

2 answers

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.