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?

3
  • 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. Commented Jun 30, 2016 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. Commented Jun 30, 2016 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 explains the issue in the general case. Commented Jun 30, 2016 at 19:44

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

Comments