1 - Optimizing Parameter Checks
❌ Stop this:
if (userRole !== 'admin' && userRole !== 'moderator' && userR...
For further actions, you may consider blocking this person and/or reporting abuse
This is a great list of suggestions! I definitely push for #1 in code reviews all the time.
I am on the fence about #2, though. There are times it's useful to pass a specific state rather than having to check to see if we need to toggle. It could be written to support an optional forced value, which would cover both possibilities.
Woah -- how had I not learned about the nullish coalescing operator
??
until today 😯I think I could sub it in for most of my
||
s and it would be more syntactically accurate.Yeah! Pretty good suggestion thank's! :)
Regarding #4 - Efficient Object Cloning
It's good to know that the spread variant won't work as expected:
That is because spreading will only do a shallow copy, but keep it's references to deep objects.
Example:
So in that case, the structuredClone is better to use.
I wish you had explained the “why” here. As-is, this reads doctrinaire, especially since constructs like
Set
are only more efficient once you achieve a greatern
size.Strongly agree on #1 and #3!
Out of curiosity, what's the benefit of going with
useReducer
overuseState
in #2?Since we use lots of toggles, I've got it abstracted out to a custom hook that lets you either just toggle it (99% of the time) or force-set a value (a few rare instances):
You can make a custom hook too, I like the useReducer way because it's simple and easily readble. As @oculus42 said, you can give a custom value if you want
The second option: why is that better?
Hi @bop! It more simple and readable :)
Good very nice
Very nice 👍
Valuable tips, the first time I saw it I identified myself lol, I'm going to apply it to reduce my gigantic ifs. Thank you very much for sharing your knowledge 🦤.
<3
Very cool
Nice article.
Thank you !!
const originalObject = {
key1: 'value1',
key2: {
key2a: () => console.log('value2a')
}
}
const objectCopy = structuredClone(originalObject) <---
I think that's maybe the old browser cannot work with
structuredClone