Function expressions in JavaScript
While I was writing the post on JavaScript functions, I realised that the “function expressions” needed a post of its own! So here I am writing about all the features, properties and uses of the function expressions. Some of these I learned while I wrote the previous post, but are definitely interesting. So here goes!
Function expressions are just functions that are not declared as one. They are assigned to a variable as an expression.
Unlike regular functions, these are treated as expressions. In this case, the function “foo” is a variable and is not hoisted on top of the scope. Hence, they can only be used once they are declared.
They have an attribute called “name” which contains the name of the function they are assigned to. Also, when the variable is assigned a named function, the name of the function is only visible within the function and not outside.
In the above example, the name factorial can be accessed inside the function. Outside the scope of the function, “factorial” is discarded and is undefined. This is useful when iterative function is needed.
The “this” context for the function expression will be the scope of the variable that is assigned the function, and not the body of the function. This is especially useful when the function is assigned as a method of an object.
In the above example, the context of the function will be the object. The output of the function assigned to variable3 will be: “Some value” and value.