Oliver Bradley Oliver Bradley - 1 year ago 57
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
to be either
but it is the length of the string. Not sure why this is?

Answer Source

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