0

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?

ifvictr
  • 141
  • 2
  • 3
  • 13
  • At first I was going to downvote, but then I realized you were getting a number instead of true, false and not the other way around. – Goose Jun 30 '16 at 19:41
  • @Juhana Is there a better more generic duplicate, because that one is specific to logical operators returning objects and wouldn't turn up in a future search of someone with this problem. – Goose Jun 30 '16 at 19:42
  • @Goose You can look for one from the linked questions of that question. The person who asked the question chose a not-so-good answer, but the [answer with the most votes](http://stackoverflow.com/a/8569966/502381) explains the issue in the general case. – JJJ Jun 30 '16 at 19:44

1 Answers1

0

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