Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you declare facultative function arguments in Javascript?

Like you can in php

<?php
function whatever($var='') {

}
?>

can you do that in javascript?

like image 845
Tom Avatar asked Nov 25 '25 23:11

Tom


2 Answers

If you want to set a 'default' value to your arguments, you can do something like this:

function whatever(arg1) {
  arg1 = arg1 || 'default value';
}

Keep in mind that the 'default value' will be set if arg1 contains any falsy value, like null, undefined, 0, false, NaN or a zero-length string "".

Also in JavaScript functions you have the arguments object, it's an array-like object that contains the arguments passed to a function, therefore you can even declare a function without input arguments, and when you call it, you can pass some to it:

function whatever() {
  var arg1 = arguments[0];
}

whatever('foo'); 

Edit: For setting a default value only if it is truly undefined, as @bobbymcr comments, you could do something like this also:

function whatever(arg1) {
  arg1 = arg1 === undefined ? 'default value' : arg1;
}
like image 51
Christian C. Salvadó Avatar answered Nov 28 '25 14:11

Christian C. Salvadó


In javascript you can call a function regardless of parameters.

In other words it's perfectly legal to declare a function like this:

 function func(par1, par3) {

   //do something
  }

and call it like this:

 func();
like image 23
Robban Avatar answered Nov 28 '25 12:11

Robban



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!