Frank suspected something odd when he spotted a use of React's useMemo function in some JavaScript code. Now, there's nothing wrong with using that method, in and of itself. It watches some variables and recalculates a callback if they change for any reason. It's a great tool for when you want to avoid recalculating expensive things over and over again.

But in this case, the calculation in question was isAuthorized, which wasn't an expensive calculation; it was just checking if certain values are set. The code looked like this:

  const isAuthorized = useMemo(() => {
    return (session && token && !group) === false;
  }, [session, token, group]);

session, token and group are all either going to be null, or be an object. To be authorized, all three must be set to non-null values. A rational person, knowing this, might choose to return session && token && group, and exploit JavaScript's truthiness. Or, if you really wanted to coerce it to a boolean, you could return !!(session && token && group).

So why on Earth are they negating group? How would this even work? If the check is "all three must be set" what is this doing?

Well, if you do a && b && c, JavaScript will return the last value you looked at. The && operator short circuits, so that means it either returns the first falsy value you encounter, or the very last value in the chain.

So in this scenario: (session && token && !group), if session or token is null, the expression evaluates to null. Otherwise, if group is null, then !group will evaluate to true. Because they use the === operator, JavaScript won't do any type coercion, and that means null === false is false, as is true === false.

I can't believe that this code works as intended. I mean, it works, it gives the correct output, but I think that's an accident. Happenstance of someone with no clue gradually throwing operators into an expression until it does what they want. Perhaps it's LLM generated code- who can even guess anymore? It certainly seems like it was generated through a stochastic process; whether that's a bumbling developer or a bunch of math, there's definitely no intelligence involved, artificial or otherwise.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!