Function Expressions in JavaScript

I was going through the function expressions module from Basic JavaScript.

I am really not able to understand the real-life use case of Function Expressions Over declaration.

Why should I prefer using function Expressions?

You don’t need to prefer function expressions over declarations. Both are important.

Function expressions can be passed as arguments to other functions. You’ll see them a lot when you get to callback functions. The idea is that sometimes you want to pass a function along to another part of your code so that it can be run that function at a later time. You can’t do this with function declarations.

what is an example of a function declaration and an example of a function expression?

Functions are first class objects whether declared or written as expressions. They can be passed by reference to other functions, not just as callback expressions.

Eg.

 > function addAB(a,b) {
       return a + b;
   }
<- undefined
 > [1,1,2,3,5,8,13,21,34,55].reduce(addAB)
<- 143

Above is a declared function which opens with the function keyword. Note there is no assignment. The singular advantage of this type of object is hoisting which means the function can be written anywhere, even at the bottom of a script, and called from anywhere, even from the top.

Expressions can be revised and re-assigned to the same variable so long as it is let not a const. A const function assignment is immutable. It cannot be changed or destroyed. This is the safest way to write persistent functions.

const addAB = (a, b) => a + b;  // Arrow function expression
const fibSumFirstTen = [1,1,2,3,5,8,13,21,34,55].reduce(addAB)
console.log(fibSumFirstTen)
//  143

Or we could write the standard function expression,

const addAB = function (a, b) {
  return a + b
}

All functions can be assigned by reference to another variable…

add = addAB
console.log(add(6, 7))    //  13

Function expressions are generally not named unless there is recursion involved (it needs to be able to call itself). For most situations they remain anonymous.

2 Likes

Thanks for the correction! So much for thinking I got Javascript mostly figured out :rofl: :rofl:

1 Like

Welcome to the club. Hardest thing is to hang on to the interesting bits because we get so little opportunity to implement them. Don’t be like me, keep good notes in a searchable database.

2 Likes