Writing code convention JS / React?
Hi, again!
In the quest to understand syntax better, a quick question.
In the example underneath, from codecademy, the function calculating the prime number is underneath the counter function reusing the prime function. In my mind it would make more sense to place the prime function above the counter function since counter uses prime. So why is it underneath? Is this a JS / React convention?
3 Replies
It depends. Normally, I would agree with you. However, when I open a react component file what I expect to see first is the React component, not some random function.
The
isPrime
function clearly is a rather generic function, not one that exclusively belongs to this one component. It's probably written below it to signify that it can be placed in a separate file for utility functions.
If this function was meant to be used exclusively by this component only, then the definition should go inside the component.Right! So this is just a consequence of the codecademy lesson structure. In a real life example this would have been done in two ways, if I understand you correct:
1.
isPrime
would be in its own file, e.g. isPrime.js
2. It would be moved inside of Counter
, and then at the top, I guess?If it's already on another file, there's no need to define it again, you would simply import it the same way you do with
useState
, useEffect
or any other file
If it's not in another file, then it would be defined inside the component. Doesn't matter where but normally that should come after the state.