Oliver Bradley Oliver Bradley - 5 months ago 7
Javascript Question

javascript: expecting true or false but getting number

I have something like the following:

var val = "string";
var testVal = val && val.length;


I would expect
testVal
to be either
true
or
false
but it is the length of the string. Not sure why this is?

Answer

The logical && operator doesn't perform a type casting. The expression it forms is just evaluated to the left-hand operand if this operand is falsy, otherwise to the right-hand operand.

You have to explicitly convert to boolean:

var testVal = !!(val && val.length);
Comments