2

I have a function in javascript :

function test(a, b, c) {
    if(typeof b == "undefined")
      //do something 
    //function code
}

Now i want to call this function in such a way so that typeof b remains undefined and a & c containes value (without reordering a, b & c), like

test("value for a",  what i can pass here so that b type will be undefined, "value for c")
1
  • 2
    Create a variable without value and use it or maybe even a non existing variable. Commented Jun 12, 2012 at 9:16

4 Answers 4

9

Simply pass undefined (without quotes):

test("value for a", undefined, "value for c");
Sign up to request clarification or add additional context in comments.

1 Comment

You shouldn't rely on undefined for control flow (especially not for arguments). The value could be legit or it could be masking an error. Yes it's what OP is asking for but guiding him in a more productive direction want harm :)
4

Any variable (that's undefined).

var undefinedVar;
test("value for a", undefinedVar, "value for b");

3 Comments

Why not just use undefined? No sane person will ever redefine it and modern engines don't allow that anyway.
Yeah could do. There's more than one way of skinning a cat though.
@ThiefMaster Minor correction: modern engines don’t allow redefining the global undefined. (function() { var undefined = 42; }()); is still allowed by the spec, and would work. See mathiasbynens.be/notes/javascript-identifiers.
4

I would suggest another approach if you know that you either pass a,b and c or you pass a and c. Then do as follows

function test(a, b, c) {
  if (arguments.length < 3){
      c = b;
      b = arguments[2]; //undefined
      //do want ever you would do if b is undefined
  }
}

In this case if you by mistake pass an undefined for b it's easier to spot because it's not interpreted as "undefined actually doesn't mean undefined but is a flag telling me to do something different" it's usually more robust to test the arguments length than to rely on the value of the parameters especially if that value can also be the result of an error (Ie. if the value is undefined)

1 Comment

agree, typeof x == "undefined" is just horrible in general as well
0

You can use void operator:

test('value for a', void 0, 'value for c');

void operator evaluates the expression and returns undefined.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.