mhmpl
mhmpl

Reputation: 1043

JavaScript boolean variable is true even if nothing is passed

I have the following if clause:

if(trackingEnabled && tracking) {
  // do something
}

Both variables are function parameters. In some cases the tracking variable is set as a boolean, in some cases not.

If I lookup the variable's type (in the case that I don't pass a value), then it is a simple Object.

My question is now, why is the tracking variable interpreted as a boolean (value is true) when I don't pass anything to the function?

Upvotes: 0

Views: 1008

Answers (1)

toske
toske

Reputation: 1754

Can you paste the whole code (method call). I've tried code below in IE9, FF14 and Chrome 23, and code inside if statemenet never gets executed, while typeof b is evaluated to either undefined and object, respectively to method calls.

function f(a,b){
 console.log("Type of b is " + typeof b);
 if(a && b){
     console.log(a);
     console.log(typeof a);
     console.log(b);
     console.log(typeof b);
 }
}
f(true);
f(true,null);

I see two possible causes

1) You have something passed in function

2) You have some weird Javascript execution environment

Upvotes: 2

Related Questions