What are the advantages of function expressions?

Yes, any object with {} is a block.

if () {}
while () {}
for () {}
switch () {}
function () {}

When we write,

a = 42

within a function, it is defined, but not declared. JS hoists this to the top of global scope meaning that any function or object has access to it. No matter how deeply nested the function is, it rises all the way up the scope chain to the window object.

foo = function () {
    a = 42
}

console.log(window.a)    //  42

console.log(a)           //  42
4 Likes

Great! Thank you very much

1 Like

@mtf mtf, you help everyone. I am your fan.

5 Likes

Thank you! This is the exact thing I was wondering about.
Before I decided to pick up JS I used to do some light modding for a few games using other languages and this concern is a strong parallel to the mod compatibility conflict headaches that would arise.

1 Like

yes true, i am a beginner in coding and am stuck at understanding how function and return exactly works. Trying to make sense of reading why function and return works this way, then come function declaration and function expression which makes it more complicated.

I think i agree that i cannot proceed until i fully understood this portion of JS.

1 Like

It’s late but I want to answer.

I think the biggest advantage about using function expressions : function expressions are useful when you want to pass a function as an argument to another function.

You have an example here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#function_expressions

1 Like

Ok, so based on your reply is it good to use Function Expressions for cleaner and more readable code?

Thank you!

Those are not my words, but a quote from the article. One might agree with that reasoning, although, from a practical standpoint expressions are both disposable (when used as callbacks) and indisposable when written as const. They can be dynamically defined on the fly or statically defined in any scope.

When the function keyword is employed they have all the properties and behaviors of a declared function. In a word, there is no disadvantage to using them, and once one consistently applies them as a habit, the old declared function is just a faint spot in the rear view mirror.

Hello, I read through most of the responses, but I still don’t understand because there are a lot of words that are being used that I don’t understand yet(i.e. global, leakage, mutated function, scoping, polluting etc.) since I am a beginner as well. The sense that I got from mtf is that functions can be deleted. I don’t understand who will be deleting the functions, if this is your personal code, or how or why functions need to be protected. I understand functions in the mathematical sense(i.e. function composition), but not in the javaScript sense of function expression. Any clarification with that doesn’t use language beyond the current function module would be greatly appreciated.

1 Like

The function declaration is not as limited in scope and is hoisted (lifted up) to the top of the current scope. Therefore this code will work fine using function declaration (but would not work with function expressions or arrow function expressions):

helloFuture();

function helloFuture() {
    console.log('Hello World');
}

You can pass either type of function (declaration or expression or arrow function) to another function as an argument.

The only similarity between a program function and a mathematical function is their exhibited behavior. Something in, something out, in a pure function sense, anyway. Math functions are always pure. Program functions are often times anything but. Intuitive programmers work to bring the same level of pure functionality to their code so it is just as declarative as math. This is a learned process, and takes lots of work to get to this level of expectation.

Some big words, or strange diction, will come up throughout any discussion concerning JS, and programming in general. A lot needs to be learned and understood to become a player in the development world. Learn as much as you can from other learners along the way, not just teachers or courses. That’s what you’ll find in these forums… Other learners.

Watching other learners struggle helps keep us from getting in too deep, too quick. We can feel free to admit that we’re struggling just as they are and can join the club. That’s how peer groups and teams begin to gel. Read their questions and admit you have the same ones. Learn alongside with them.

This is a very loaded question since so many terms and concepts come up in one go. One can see how it would be overwhelming to any learner. Let’s try to make this brief…

Start with any web page on the modern internet. Look around that page. There are probably a dozen different segments that are seemingly independent of one another. That may be so except from one small detail… All their code base name references exist in the same place in memory, the global namespace.

When scripts are loaded from several sources, there is always the possibility that their variables could collide with something already present in our script. That would be a huge disaster, whether the names reference values or functions. Do we want plug-ins to be messing with our own script behaviors? Na-ah-ahhhah! Hence the need to protect them.

Now we know that ‘global’ means the very environment where everything is rooted. The global namespace is where we find the names of everything given a reference in this environment. Global sort of means, ‘for all things concerned’, and all objects in this scope are accessible from anywhere in our program.

Mutation means change, and in programming that usually means evolved through multiple iterations over the same data structure. When we change the value of an element in an array, add to or delete a value from the array, we mutate that array. It’s still an array, but the contents have been altered.

Obviously any change to anything could be called mutation. For our purposes, if it is not an array or object, it is a set event, rather than a mutation. We are changing a state. Mutation means a data structure has changed.

If we’re getting anything of a grasp on this subject it’s clear we’re dealing with memory and memory management, although in JS we don’t have a direct hand in it. We manage memory by how we scope our variables. Functions offer us a means to request and release memory resources. It is when we fail to manage well that things get left in unreleased memory. This is the definition of leakage. It is lost memory. Excessive leakage can slow down a page, both in loading and in interaction.

As for polluting, that points directly to memory leakage, leaving detritus in the global namespace which pollutes that environment.

3 Likes

Another difference where function expressions have an advantage is that they can be anonymous and self-invoking. This does not apply for function definition. The benefit is that the function and variables it contained are gone after it has executed. The syntax for doing this is a bit odd and includes wrapping the function expression in parentheses followed by another parenthesis. Note that this is a function expression since it’s anonymous and not named:

// Function expression - can be anonymous
(function () {
    let briefMsg = 'I am invoking myself!';
    console.log(briefMsg);
  })();

That would make one weird return value, to be sure. It would help if we had a little more explanation than that it offers some advantage. Please elucidate.

Weird return value? In that case the function is not returning anything so it’s defaulting to returning undefined. You can paste it into the console and confirm. It was just a very basic function with side-effects (console.log) to demonstrate the self-invoking syntax you may come across in the world of JS. I think one reason to use the self-invoking syntax is that after it’s done there is no reference to the function name or anything related to the function as it is “destroyed” after it’s executed. Personally, I find it somewhat hard to read so I don’t really use it.

Granted, there are use cases for IIFEs, though at this stage the subject is a little more advanced than learners are prepared for. I’m not sure this course even touches upon closures or aliasing, which are common uses.

Ultimately it would be pointless to wrap a simple procedure in an IIFE. A simple statement would fill the same role.

@mtf Thank you. I was confused about the Function Expressions as well.

1 Like

The only advantage I can see is to prevent writing over a function. I did some C# tuts for fun and if you write two functions with the same name you get an error. It seems required, but I am still not a fan of it. Assuming you don’t write over your functions wouldn’t you be just fine?

this works on the assumption you work alone. Projects are often worked on by multiple people

furthermore, you might use libraries/packages (functions written by others), where you do not know all the functions. So not being able to overwrite a function is a good safe-guard

You will see uses once you start learning to react. It make code clean and readable.

Before I come to your question, let me put this here. Function expressions differ from function declarations by name and hoisting power, in that a function declaration carries the name and can be hoisted whereas a function expression has no name and the function can never be called above their line of expression, this alone is a powerful concept in programming when it comes to code quality and easy debugging.
Now to your Question. A function declaration will be available to your entire application — there’s no need for that. But if you do a callback for a function expression, it will not be available outside of the function that uses it so with that said a function expression is needed where you want to perform a particular task with a
certain put of the application without making the function available to your entire application file.
Further Reading

1 Like