Pavel T
Pavel T

Reputation: 97

If statement shorter logic

I'm writing some code to decide whether it needs to use mock data. Here is the code:

let useMocks = false

const setMockSwitch = ({idNumber}) => {
    if (idNumber && idNumber === mockUser.idNumber) {
        useMocks = true
    }

    if (idNumber && idNumber !== mockUser.idNumber) {
        useMocks = false
    }
}

in case idNumber is passed to the function and it equals to a mockUser than "toggle" the switch...

I'm trying to think about logical solution how to shorten the code and make it more readable. I'll appreciate your help! Thanks!

Upvotes: 0

Views: 85

Answers (3)

Avin Kavish
Avin Kavish

Reputation: 8947

You can reduce this to a single line arrow function. By leveraging the short-circuit && operator you can make sure useMocks is set only if idNumber is defined

let useMocks = false

const setMockSwitch = ({idNumber}) => idNumber && (useMocks = idNumber === mockUser.idNumber)

You can also write it to be side-effect free, like so,

const shouldUseMocks = ({idNumber}) => idNumber === mockUser.idNumber

idNumber && useMocks = shouldUseMocks({idNumber})

This allows you to extract this method into a library of helpers, and re-use it, as it does not directly modify variables from the outer scope. This would be my preferred and recommended way.

If you want to account for 0 being a valid idNumber,

let useMocks = false

const setMockSwitch = ({idNumber}) => idNumber !== void 0 && (useMocks = idNumber === mockUser.idNumber)

void 0 always returns the true primitive undefined and not any local variables called undefined, therefore is the cleanest way to check for undefined. In fact you can place the void operator in front of any other expression to force it to return undefined

Upvotes: 0

nice_dev
nice_dev

Reputation: 17835

Assuming mockUser.idNumber has the actual value you are looking for, you could just do,

const setMockSwitch = ({idNumber}) => {
     useMocks = idNumber === mockUser.idNumber;
}

Upvotes: 0

Pointy
Pointy

Reputation: 414036

Well you could just take advantage of the fact that comparisons produce boolean values:

const setMockSwitch = ({idNumber}) => {
  if (idNumber)
    useMocks = idNumber === mockUser.idNumber;
};

Oh and note that if mockUser.idNumber can ever be 0, this will have problems (as would the original code) because 0 tests as false in code like this.

Upvotes: 4

Related Questions