'How to refactor code using if condition in javascript?

i have code like below,

React.useMemo(() => {
    if (isInProgress && data && data.Run) {
        if (data.Run.partial === true) { //how can i rewrite this
            setIsRunPartial(true);
        }
        else {
            setIsRunPartial(false);
        }
    } 

}, [data, isInProgress]);

here the data.Run.partial can be undefined true or false. how can rewrite above code to look clean. i have to call setIsRunPartial to true if data.Run.partial is true and false if data.Run.partial is false.

how can rewrite above code. could someone help me with this. thanks.



Solution 1:[1]

You could just take the value, if you have already a boolean type.

setIsRunPartial(data.Run.partial);

Solution 2:[2]

How about

React.useMemo(() => {
    if (isInProgress && data && data.Run && data.Run.partial) {
        setIsRunPartial(data.Run.partial);
    } 

}, [data, isInProgress]);

If you are using babel and open to adding the @babel/plugin-proposal-optional-chaining package, this can even become

React.useMemo(() => {
    if (isInProgress && data?.Run?.partial) {
        setIsRunPartial(data.Run.partial);
    } 

}, [data, isInProgress]);

Solution 3:[3]

You can simply use setIsRunPartial(!!data.Run.partial)

If it is undefined, the !! boolean cast will make it become False --> setIsRunpartial(false) in case of undefined

Other than that, if true or other truthy value --> setIsRunPartial(!!truthy) -->setIsRunPartial(true)

if false or other falsy value --> setIsRunPartial(!!falsy) -->setIsRunPartial(false)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nina Scholz
Solution 2 Simeon Gavalyugov
Solution 3