King Kong
King Kong

Reputation: 2915

Calling javascript function with undefined value

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")

Upvotes: 2

Views: 221

Answers (4)

Engineer
Engineer

Reputation: 48793

You can use void operator:

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

void operator evaluates the expression and returns undefined.

Upvotes: 0

Rune FS
Rune FS

Reputation: 21742

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)

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318468

Simply pass undefined (without quotes):

test("value for a", undefined, "value for c");

Upvotes: 9

ahren
ahren

Reputation: 16961

Any variable (that's undefined).

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

Upvotes: 4

Related Questions