Ad

Behavior For Single If Condition (omitting Else Return False)

- 1 answer

I was able to omit the else return false for this React lifecycle method and still have it work as desired, returning false for odd numbers (value increments by 1 from 0 -- see freeCodeCamp challenge for the rest of the code), but I'm not clear on why it works this way.

shouldComponentUpdate(nextProps, nextState) {
    console.log('Should I update?');
    if (nextProps.value % 2 == 0) return true;
  }

Since shouldComponentUpdate defaults to true per React docs, I thought it might still return true even for odd values. I guess the default only applies when there is no condition specified whatsoever.

If an if condition that returns true isn't met and no other conditions are provided, does JavaScript always return false?

Ad

Answer

If an if condition that returns true isn't met and no other conditions are provided, does JavaScript always return false?

The short and literal answer is no. JavaScript values (even booleans) can be evaluated as truthy or falsy.

With this said, lets try to analyze what is happening in your component method.

  • A JavaScript function with no return statement evaluates to undefined.

  • shouldComponentUpdate in React expects a boolean value.

  • Since the function returned undefined, it is evaluated as a falsy value automatically.

  • Then the component isn't updated due to the falsy value return.

My recommendation:

Take control of your code.

Avoid unexpected behaviors like this since it may change in future versions of React.

Why not a ternary conditional?:

shouldComponentUpdate(nextProps, nextState) {
   return (nextProps.value % 2 == 0 ? true : false);
}
Ad
source: stackoverflow.com
Ad