DEV Community

Discussion on: Everything You Need to Know About JavaScript Functions

almostconverge profile image
Peter Ellis

Nice summary of a concept that may seem complicated and alien at first, depending on your past experience.

What I would add to the post is: why does all this matter?

Well, apart from the obvious that organising stuff into functions is essential for good code, the big strength of how functions work in JS is the ability to pass functions around as any other value. (As seen in the squareofsums() example.)

This may not seem like a big deal at first but it opens up an incredible range of possibilities, for example:

function executeWithErrorHandling(operation, errorhandler) {
  try {
  } catch (e) {

const consoleErrorHandler = e => console.error('complicated operation failed', e);

const complicatedFunctionThatMayThrowError = ...;

executeWithErrorHandling(complicatedFunctionThatMayThrowError, consoleErrorHandler);
Enter fullscreen mode Exit fullscreen mode

So now if you want to, you can replace your error handler at any time to a different one without having to modify complicatedFunctionThatMayThrowError().

aravsanj profile image
Aravind Sanjeev Author

Thanks for taking time to reply. This is a great hack and a practical example of function expression's abilities (as we can pass them as arguments to other functions). It is also important to note that through this method, we can also avoid polluting the global scope. Function expressions are used and forgotten.

We can also create immediately invoke a function expressions like this:

(() => {console.log("Hello")})()
// Hello
Enter fullscreen mode Exit fullscreen mode