default argument in javascript function [duplicate]

2

Which of these, or other, is the best way to set the default value of a javascript function?

function func(arg){
   //Esse:
   arg = arg || "valor padrão";
   //Ou esse:
   if(arg === void 0 ) { arg = "valor padrão"}
   //Ou esse:
   arg = arguments.length > 0 ? arguments[0] : "valor padrão";
}
    
asked by anonymous 24.08.2018 / 04:07

3 answers

3

The previously mentioned default parameter (default parameter) is a good output:

function foo(bar = 1) {
     console.log(bar);
}

foo();
foo('oi');

However, what no one has quoted yet is that will not work in older browsers , such as:

  • Internet Explorer (same as 11)
  • Safari 9 (or older)

And it probably will not work on some native Android browsers, so if you intend to give support without wanting to take risks use typeof yourself, or you can use IIEF (Immediately Invoked Function Expression), like this:

/*
w = window
d = document
u = undefined
*/
(function (w, d, u) {
    w.minhaFuncao = function (a, b, c) {
          a = a === u ? 'valor padrão para "a"' : a;
          b = b === u ? 'valor padrão para "b"' : b;
          c = c === u ? 'valor padrão para "c"' : c;
          
          console.log('/a => ', a, '/b => ', b, '/c => ', c);
    };

    w.minhaOutraFuncao = function (foo, bar) {
          foo = foo === u ? 1 : foo;
          bar = bar === u ? 1 : bar;
          
          console.log('/foo => ', foo, '/bar => ', bar);
    };
})(window, document);

minhaFuncao();
minhaFuncao('A');
minhaFuncao('A', 'B');
minhaFuncao('A', 'B', 'C');

minhaOutraFuncao();
minhaOutraFuncao('FOO');
minhaOutraFuncao('FOO', 'BAR');
    
24.08.2018 / 04:44
1

In reality it would look like this:

function func(parametro = 'valor padrão') {

}

It is not very good to use arg or args as parameter name too.

    
24.08.2018 / 04:16
1

For security, I think you'd better tell the method constructor.

The example arg = arg || "valor padrão"; would generate an instability if the parameter type was boolean or a numeric, "if you entered false or 0, it would assume a default value".

You can either use the typeof or else be declaring in the method constructor, examples below:

  

In the method constructor (I recommend):

function teste(param = 'valor padrão') {
     console.log(param);
}

teste(); // imprime a string valor padrão no console.
teste('oi'); // imprime a string oi no console.
  

Using typeof:

function teste(param) {
     if(typeof param === 'undefined') {
          param = 'valor padrão';
     }
     console.log(param);
}

teste(); // imprime a string valor padrão no console.
teste('oi'); // imprime a string oi no console.
    
24.08.2018 / 04:23