Required Functions and Optional Variables

In PHP, we can specify the default value of a variable in a function, for example:

function myFunction(myDefaultVariable, myOtherVariable, myCheckVariable = "basic"){
    // so yeah, myDefaultVariable is required always,
    // same applies for myOtherVariable,
    // and myCheckVariable can be skipped in function call, because it has a default value already specified.
}

Is there something similar in JavaScript?

+3
source share
3 answers

You do not need to pass all variables to Javascript.

Although a less dangerous way would be to use objects:

function foo(args) {
    var text = args.text || 'Bar';

    alert(text);
}

To call it:

foo({ text: 'Hello' }); // will alert "Hello"
foo(); // will alert "Bar" as it was assigned if args.text was null
+9
source

not really, but you can simulate it by checking if a value was passed and a default value was set, for example

optionalArg = (typeof optionalArg == "undefined")?'defaultValue':optionalArg

Note that such a method works even when the optionalArg option is provided, but evaluates to false - what happens with a simpler idiom like optionalArg=optionalArg || 'default'.

arguments, , , , .

+4

No, which I know about:

But there are two ways to solve this problem.

//1. function.arguments - this is advisable if you don't know the 
//   maximum number of passed arguments.

function foo() {
  var argv = foo.arguments;
  var argc = argv.length;
  for (var i = 0; i < argc; i++) {
    alert("Argument " + i + " = " + argv[i]);
   }
}

foo('hello', 'world');

//2. "Or" operator - this is good for functions where you know the
//   details of the optional variable(s).

function foo (word1, word2) {
   word2 = word2 || 'world';
   alert (word1 + ' ' + word2);
}

foo ('hello'); // Alerts "hello world"
+1
source

Source: https://habr.com/ru/post/1763569/


All Articles