Default in function parameters in JavaScript [duplicate]

3

Is it possible to make parameter defaults in JavaScript functions? Something like:

function teste(oi = "ola", type = 1) {

How do I predefine the variables if they are not defined?

    
asked by anonymous 02.04.2015 / 03:38

2 answers

4

There are several ways to do this, one of which is as follows:

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
}

NOTE: Reposted copied from original Tom Ritter on: a link="https://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function"> link

    
02.04.2015 / 03:55
3

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

If you are going to use this a lot, you can create a function to simplify this syntax. Something like this:

function def(variable, value) {
    return (typeof(variable) === "undefined" || === null) ? value : variable;
}

Here's how it would work:

function teste(oi, type) {
    oi = def(oi, "ola");
    type = def(type, 1);
    //continua a função aqui

There is an experimental way to get a syntax in the language as MDN documentation >. This way you could use it the way you want it. At the moment it only works in FireFox.

    
02.04.2015 / 03:53