5

After taking over a project from someone else, written in Javascript. One line I see everywhere is if statements using !+msg. From testing I can see that it checks to see if there is more than one word or not, but I was hoping someone could explain why this works. Thanks!

1
  • 1
    It's difficult to give a contextually informative answer because nobody knows what sort of value msg might contain, or why. Commented Apr 6, 2020 at 18:16

1 Answer 1

8

The + operator coerces its operand to a number, and the ! operator coerces its operand to a boolean value and inverts its sense (false -> true or vice-versa). Thus !+msg means, "if the value of msg interpreted as a number is 0 or NaN, the value should be true, otherwise false."

Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.