50

I want to pass the value of 'undefined' on a multiple parameter function but without omitting the parameter.

What do I mean with "without omitting the parameter". I mean that we should not just omit the parm2 like this example:

function myFunction (parm1, parm2) {}
myFunction("abc");

This will indeed make parm2 undefined, but I am not allowed to do it this way because I will need to specify other parameters AFTER the omitted parameter, so the previous method won't work in the case I want to make parm1 undefined BUT also want to have other parameters after this one to hold a value.

I have tried solving the problem with:

myFunction( ,"abc"); //doesn't seem to work

Update:

and myFunction(undefined, "abc"); « this reliably works now.

However, it is worth mentioning that:

Setting a variable to undefined is considered a bad practice, we should be using null instead.

ajax333221
  • 11,436
  • 16
  • 61
  • 95

12 Answers12

68

myFunction(undefined,"abc"); this way should work, what is the problem?

see here

Here is undefined documentation from mozilla, supported by all browsers

Kostanos
  • 9,615
  • 4
  • 51
  • 65
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • Why would undefined being non-writable make a difference? That doesn't affect passing it into a function. – Ted Bigham Sep 04 '15 at 21:00
  • @TedBigham it being not writable means that it can't be set to a value somewhere previously in the code, meaning (based on the spec) that it should always be considered undefined – Brian Leishman Apr 19 '16 at 14:30
  • @BrianLeishman I agree you can't assign a value to the undefined keyword, but that should have no effect on passing it as an argument to a function. – Ted Bigham Apr 20 '16 at 00:24
  • @TedBigham I think the point was that you can use it safely. Like for example I could pass `kfdjhsdfgsdf` to a function because it probably hasn't been defined, but there's a possibility that it has a value and may have unintended results if used with the notion that it isn't defined, whereas `undefined` cannot be set and shouldn't have unintended results – Brian Leishman Apr 20 '16 at 13:53
  • 5
    Setting a variable to `undefined` is considered a **bad practice**. You should pass a `null` value. More info at [What is the difference between null and undefined in JavaScript?](http://stackoverflow.com/a/5076962/1549837) – Carlos Morales Sep 30 '16 at 08:19
15

The void operator seems to be the most common way to explicitly get undefined.

You would use it like this in your example:

myFunction(void 0, "abc");

It's also a reliable method for comparing against undefined that is guarded against undefined being accidentally overridden in older JavaScript environments:

var x;
if (x === void 0) {
    // this will execute
}
bkbooth
  • 498
  • 3
  • 13
12

A better approach might be passing Object with named attributes and then look for those specific attribute values. This way you don't have to be dependent on number of arguments.
Example: Object.dummy

Sanketh. K. Jain
  • 489
  • 1
  • 9
  • 24
dbrin
  • 15,525
  • 4
  • 56
  • 83
  • 2
    +1 for suggesting that the function in question could be rewritten. – davidchambers Jan 25 '12 at 07:19
  • 6
    It's not a bad suggestion, but it's a bit arrogant to suggest this is *always* a better approach, and it doesn't actually answer the question. – Jonathan Hall Jun 05 '14 at 22:39
  • 2
    Noone said its always better. I don't see what you find arrogant about the answer, it's simply another way to pass in parameters that avoids the issue of positional parameters. – dbrin Jun 05 '14 at 23:04
  • Traditional function arguments are better to get used to. – Tomáš Zato Oct 23 '14 at 06:08
  • Would be extra great answer with a small example of how to do this. – alphapilgrim Dec 21 '15 at 22:49
  • That is actually genius, why haven't I never thought of that. My thanks @dbrin – Backer Oct 20 '16 at 08:56
  • Even if this suggestion is nice, you'll not be able to change any 3rd party function where you need to pass parameters on the raw. I think @bkbooth solution should be marked as correct answer. – Kostanos Jan 10 '17 at 01:41
  • It's the worst idea for readability to use `Object.dummy` as `undefined`. – poletaew Nov 06 '18 at 13:58
  • @poletaew : He doesn't mean to use Object.dummy as undefined. He meant use optional params style by wrapping in a object. – Ayyappa Aug 29 '19 at 19:29
3

You need to handle the function call with undefined variable in the function code itself in one of the following way :-

 function myFunction (parm1, parm2) {

         if (parm1 !== undefined) {
             // execute code if 1st param is undefined
        }

         if (parm2 !== undefined) {
             // execute code if 2 param is undefined
        }

        // execute other part of code

    }

Now you can call the above function in following ways:-

myFunction(undefined,"abc"); // with 1st param value not known

myFunction("cde",undefined); // with 2nd param value not known

myFunction("cde","abc");  // with both param value known
Nipun Madan
  • 169
  • 1
  • 10
3

I just had an idea and it seems to work:

var undf;

myFunction(undf, "abc");

I am sure there are better ways, however I post this

ajax333221
  • 11,436
  • 16
  • 61
  • 95
2

I think the closest you'll get to this is passing null as a parameter. It's not undefined, but for most cases it's close enough.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

If its possible , could you rearrange the function as myFunction (parm2, parm1)

ie. try to ensure possible undefined parameters are last in the function , this might not work if more parameters are introduced.

1

You can use apply and an array of parameters to pass "undefined" as one of the parameters. For example, you wanted to pass parm1 as "undefined":

function myFunction (parm1, parm2) {

    if(typeof (parm1) === "undefined"){
        alert("parm1 is undefined")
    }

    if(typeof (parm2) === "undefined"){
        alert("parm2 is undefined")
    }

}

var myParameters = [undefined, "abc"];

myFunction.apply(valueForThis, myParameters );
Edward Olamisan
  • 800
  • 1
  • 18
  • 28
1

Try to use this method if you plan on adding an indefinite amount of parameters:

function myFunc(params) {
    // Define default values
    var name = 'John';
    var age = '40';
    // You can loop through them
    for (var p in params) {
        alert(p + ':' + params[p]);
    }
    // And read them in like this
    if (typeof params.name != 'undefined') {
        name = params.name;
    }
    if (typeof params.age != 'undefined') {
        age = params.age;
    }
    alert(name + ' ' + age);
}

alert('test1');
myFunc({name:'Bob', age:'30'});
alert('test2');
myFunc({name:'Bob'});
Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96
0

An easy way of doing this, when acceptable is to pass undefined. But better yet as follows per W3C

Javascript-missing arguments

function myFunction(x, y) {
if (y === undefined) {
      y = 0;
    } 
}
alphapilgrim
  • 3,761
  • 8
  • 29
  • 58
0

Just to give an examples on what @dbrin was explaining, and @alphapilgrim might have wished to check.

simpleFunction({params1:12, params2:"abc"}); //use expected arguments
simpleFunction({params2:"abc"}); //use only one
simpleFunction({params2:"abc", params1:12, iDoNotExist:"I will not be included"}); //use expected arguments in any order
simpleFunction(); //ignore arguments and uses defaults
simpleFunction(2123); //ignores non object arguments 

function simpleFunction(someParams){
  var myParams = {
    params1:null,
    params2:"cde" //default value for second parameter
  };
  simpleExtend(myParams, someParams);
  
  console.log(myParams);

}


//to include in your utilities
function simpleExtend(currentParams, newParams){
  
  if(typeof currentParams !== "undefined" && typeof newParams !== "undefined"){
    Object.keys(newParams).forEach(function(key){
   
      if(typeof currentParams[key] !== "undefined"){
        currentParams[key] = newParams[key];    
      }

    });
 
  
  }
  
 

}
MFAL
  • 1,090
  • 13
  • 19
0

myFunction(undefined,"abc") should absolutely work, unless someone cruel has redefined undefined! If you want to be safe, there are dozens of ways to get the undefined value which avoid the assumption that the thing called "undefined" does in fact have the special undefined value:

void 0
var undef; undef
[][0]
{}.foo
// `undef` is guaranteed to have the undefined value within this closure
(function(undef){ undef }())
// this expression evaluates as undefined
(function(){}())

void 0 is the most widely used (compiled CoffeeScript includes this wherever the undefined value is required).

davidchambers
  • 23,918
  • 16
  • 76
  • 105
  • That's good to know, although we'll be supporting older JavaScript engines for quite some time. – davidchambers Feb 04 '12 at 03:33
  • 1
    Late comment, but for others reading this: being non-writable has absolutely nothing to do with the ability to pass `undefined` directly to a function. While `undefined` is certainly non-writable, it's irrelevant to this question. – michael Apr 08 '16 at 17:10