2

my first question here! Apologies if a duplicate - couldn't find an answer.

I'm a beginner in JavaScript, currently doing some exercises and I've just ran across a line I can't grasp the meaning of. Here it is:

!+x && x !== '0'

What does !+x perform here? Line's an excerpt from a script that validates IP adresses.

Thank you in advance!

2
  • 2
    Unary + makes it a number if possible, ! negates its truthy or falsy value. Basically it’s an attempt to check if x is a number. Commented Mar 18, 2020 at 8:11
  • Thank you Sami Kuhmonen! Simple and to the point. Commented Mar 18, 2020 at 8:17

1 Answer 1

4

It checks if the x variable, when converted into a number, is falsey (0 or NaN), and isn't the literal string '0'.

Eg '0.00' will fulfill the conditions, as will 'foo', but '0' won't.

The + is unary +, converting the expression that follows into a number. Then the ! negates the boolean value of that number.

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

Comments

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.