Behavior For Single If Condition (omitting Else Return False)
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?
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 toundefined
.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);
}
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM