0

I came across a condition which made me strange. I am working on React in that I have given a condition on a render method like this:

 if (!this.props.allYearData || !this.props.Growth)
      return <Loading />;

However, my page always shows the loading symbol. I console data what I have given in if condition and both data was in define state, but my Growth was showing 0 value., so I commented out this.props.Growth and my page loaded. So I am just wondering why JavasSript didn't consider 0 as a defined value? I always has impression that ! means undefined. Can someone explain this?

1

2 Answers 2

3

0 is falsy. ! is a negation operator. Thus !0 is going to be "not falsy" or truthy. Truthy values in an if statement condition result in the if block will be evaluated.


Details

See MDN for more information on Truthy/Falsy.

Here are a few examples:

true     // truthy
false    // falsy
!true    // falsy (negation operator, it says "opposite of")
!false   // truthy
0        // falsy (this is because booleans are represented as 0 and 1 in binary,
         //        0 being false)
!0       // truthy
undefined // falsy
!undefined // truthy
Sign up to request clarification or add additional context in comments.

3 Comments

can you please bit elaborate it?
Putting ! in front of something "negates" it, i.e. makes it "the opposite". If you have something that is true, putting an ! in front of it will make it ?false: !true === false, for instance. 0` is considered false, so if you put ! in front of something false, it becomes true.
JavaScript will evaluate a number of things to false - The number 0, an empty string, NaN, and undefined will all evaluate to false. negating a falsey value results in true. It's best to be careful about how you evaluate values because these so called "falsey" values (values that are not "false" but evaluate to false) can cause unexpected results. A more specific test will often prevent this.
2

Your impression of the ! operator is fairly off in JS (and most other languages). It doesn't mean undefined, it generally always means "not", so:

if (!condition)

means "if condition is not true"

false, undefined, null, 0 and an empty string like '' will all return "falsey" in javascript if used in a conditional operator like if, while everything else will return "truthy". This is a fairly standard practice in most loosely typed languages, you find similar behavior in python, though one important difference is that in JS, an empty array is NOT falsey, whereas in python it is.

If you ONLY want to know if the value is not undefined, it's simple:

 if (this.props.allYearData !== undefined || this.props.Growth !== undefined)

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.