Call javascript function with null parameter

1

The verificaCampoVazios function has two parameters ( fs and campos ).

verificaCamposVazios = function (fs, campos)
{
 console.log(campos[0]);
}

Example of how function is called:

verificaCamposVazios(fsInformacaoCandidatoDados, ArrayCamposNaoObrigatorios);

How do I call the function without passing the parameter campos ?

I called the function like this:

verificaCamposVazios(fsInformacaoCandidatoDados);

And the function did not execute, but did not show error in console.log of Chrome .

I would like to understand how I call the function without passing an argument.

    
asked by anonymous 22.12.2015 / 17:05

2 answers

3

You can use null as an argument:

verificaCamposVazios(fsInformacaoCandidatoDados, null);

But usually the lack of this should not be any problem, because the omitted value will be null anyway.

In the specific case of the question, it may be a feature of the function itself to react differently based on the number of parameters, based on the function arguments.length .

For example, the calling function might have something like this:

if( arguments.length < 2 ) {
   ... retorna sem fazer nada ...

What would be a specificity of the function itself, not of the null itself.

    
22.12.2015 / 17:09
2

You can call a function with missing parameters with no problem, it's even a practice (as far as I know) for optional parameters, the only thing you should do to avoid errors is to check that the parameter is not undefined inside of its function.

verificaCamposVazios = function (fs, campos)
{
    if (campos !== undefined) {
        console.log(campos[0]);
    }    
}

To call the function, you do not need to pass the second parameter or pass it as null .

verificaCamposVazios(fsInformacaoCandidatoDados);
    
22.12.2015 / 17:12