Hey Olivier, good catch! Yes that would be an issue - it would need to be a function declaration which would make it work via hoisting - I'll update the example (I'll admit I didn't actually run any of this code - it was more to illustrate the concepts - so there may be other runtime errors 😬).
But, I do think that declaring a function right after it's used is a good pattern. It follows the "Stepdown Rule" described in the book Clean Code. The idea is code should read like a top-to-bottom narrative, which I do kind of like. More examples here: dzone.com/articles/the-stepdown-rule
Generally I think the most important thing is that related functions live close together in the code...whether they are before or after is less of a concern.
I agree with you: the top-to-bottom narrative works better. Declaring such functions before they are used makes you wonder what’s happening, before you see the usage, when you read the code.
And I think the way the code is set now is good. My brain is not bothered by the function being declared after it’s used, even if it’s inside the current scope, because it’s a function declaration.
P.S. no worries about not having run the examples. You’re right, they’re illustrations. I was just curious about that particular case as I found it surprising (then again, programming languages are full of surprises) and I’m not a JS expert.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hey Olivier, good catch! Yes that would be an issue - it would need to be a function declaration which would make it work via hoisting - I'll update the example (I'll admit I didn't actually run any of this code - it was more to illustrate the concepts - so there may be other runtime errors 😬).
But, I do think that declaring a function right after it's used is a good pattern. It follows the "Stepdown Rule" described in the book Clean Code. The idea is code should read like a top-to-bottom narrative, which I do kind of like. More examples here: dzone.com/articles/the-stepdown-rule
Generally I think the most important thing is that related functions live close together in the code...whether they are before or after is less of a concern.
I agree with you: the top-to-bottom narrative works better. Declaring such functions before they are used makes you wonder what’s happening, before you see the usage, when you read the code.
And I think the way the code is set now is good. My brain is not bothered by the function being declared after it’s used, even if it’s inside the current scope, because it’s a function declaration.
P.S. no worries about not having run the examples. You’re right, they’re illustrations. I was just curious about that particular case as I found it surprising (then again, programming languages are full of surprises) and I’m not a JS expert.