Confusion over anonymous functions

Confusion over anonymous functions
0

I am confused by anonymous functions. In this example:

const test = function(par1) {
  return par1;

What is test? If it’s not a function, is it a variable?

And if I call test, it won’t work, correct? How do I call the function if it doesn’t have a name?

1 Like

Anonymous functions - are functions without names.

The general syntax is like:

function functionName(parameters) {
    // code to be executed
}

For anonymous functions functionName can be omitted. Then the syntax is shorthanded to:

function (parameters) {
   // code to be executed
}

In your code example: test is a variable. Functions stored in variables are always called using the variable name:

test(parameters);

And of course you have missed closing brackets and semicolon }; in the end.

4 Likes

As @timagixe has pointed out, test is a variable name that holds the function, so it’ll work just fine. It’s the same as writing:

function test(par1) {
  return par1;}

(There’s actually a slight difference which you can read about here)

In both cases, you can call the function like so: test("some argument") and it will return the string “some argument”. Just be careful when to call the function from a variable to always call it with the brackets (and in this case, a parameter), otherwise it’ll return the function declaration. :slight_smile:

2 Likes

@timagixe

Thanks for the explanation- but when I call the variable (with an argument), it doesn’t seem to work:

const test = function(par1) {
  return par1;
}
  test('hi');

@kristina_v Thank you. I have read about that difference (and generally understand that function expressions may be a better practice as it keeps code easier to “keep straight”.

Is it correct to say then that a function expression always uses a variable? Also, I was confused by what you wrote regarding that when calling the function via a variable, you need brackets? As opposed to parentheses?

1 Like

It does work. You’re just not doing anything to the function’s return value. It’s the same with your previous question: Why doesn't this function return anything?

1 Like

Thanks I see my error there. I tried to pass an argument to the function, but when I log it, it’s logging the declaration apparently? (which I guess is what @kristina_v was referring to?

But I have included a return value in the function, and I’ve passed an argument to it. I tried to put brackets around it but I’m not sure I did it correctly. What am I missing with this:

const test = function(par1) {
  return par1;
};
  test ('hi');
console.log(test);

Yes, sorry, I meant parentheses, like (). The thing is, when you call test('hi');, you’re not doing anything with the return value, so it just goes on unused.

However, if you try this: console.log(test('hi'));, you should see “hi” written in the console. Or, you can save it in a variable, like so:

var myVar = test('hi'); //stores the string 'hi'
console.log(myVar); //prints out 'hi' into the console
console.log(test('hi')); //also prints out 'hi'
console.log(test); //prints out --> function(par1) {return par1};

Hope this clears things up a bit and sorry again for the confusion :sweat_smile:

2 Likes

@kristina_v Thank you and don’t worry about the confusion. What I don’t understand is:

If I pass the argument 'hi' to test like this:

test ('hi');

why I would need to “re-pass” the argument 'hi' to test in:

console.log(test('hi'));

Wasn’t the argument already passed? And re: saving the argument to the variable, wouldn’t that prevent me from changing it, if I wanted to call the function again with a different argument? Thank you, I appreciate the help!!!

When you call a function, like so:

const myVar = test("hi");

you have passed the return value of your function (the function named test, called with the parameter “hi”), and stored it into a variable named myVar. But that doesn’t mean you’ve stored the function itself, merely its return value.

Each time you call the function, it executes again. With whatever you pass as your parameter. In the case of

console.log(test('hi') );

we are calling the function, and then we log whatever value it returns. When that value has been returned, our function no longer exists in memory. We haven’t stored a reference to this particular run of the function, we have simply run the function, got a value, and the browser’s memory management tools will “garbage collect” our now-used function for us.

There are ways of doing what you’re suggesting - creating a function that stores a value, and can simply be called with no value later - but they’re a bit more complex. What happens in that case is, when we call the function for the first time, it creates a space in memory (often called a “scope”), kind of a function context, and then it returns an function (rather than returning a static value). Here’s an example of that:

// this outer function takes in a variable, creates a function scope, 
//   and then passes back the inner function. By passing the function back, we have a way
//   to access the parameters we've "stored" in our function scope.
var saySomething = function(whatToSay){
  // this function has access to the parameters we've passed, even after the function itself has
  //  run. So long as we have something that refers into this memory space, the browser's
  //  garbage collection will leave it alone.
  return function(whoToSayItTo){
    // this function also takes a parameter, but it can still access the outer function's as well!
    return whatToSay+" "+whoToSayItTo;
  }
}

// Here's how it might be used:
let sayHelloTo = saySomething("Hello");
let sayHelloInItalianTo = saySomething("Buon Giorno");
let sayHelloInBrazilianTo = saySomething("Bom dia");

// Each of the above functions created a unique space. Each is stored.
console.log(sayHelloTo("world!")
console.log(sayHelloInItalianTo("terre!")

const myVar = sayHelloInBrazilianTo("Bob");
console.log(myVar);

A little deep, but that’s a bit of an answer to the question of “why are my parameters not being kept?!?”

1 Like

The test('hi'); basically doesn’t do anything. I mean, it returns ‘hi’, but you never save it or use it, so it’s value is forgotten. As @snowmonkey explained, every time you call a function, you’re making a separate call. Maybe it’s confusing because we’ve been using the same string as an argument in all of the examples :sweat_smile:

2 Likes

@snowmonkey Thanks so much for the thorough response! I’m slowly trying to get it into my head… I’m sure I will revisit your answer!

1 Like

@kristina_v Thanks for all the responses. Ok, I think I’m slowly understanding (at least some of it!). I guess my main takeaway here is what you said: “every time you call a function, you’re making a separate call.”

2 Likes

I find it easier to understand functions when I think in terms of input, process, and output. Input is the parameters that the function accepts. Process is the code in the function; how it acts on the input. Output is the result, the return value. You can think of a function as a box, a black box. You put something in it (input, parameters), and it spits something out (output, return value). When you invoke, or call, a function you pass in parameters, for example, myFunc(input). When the function completes its process, it returns the output: return result;. The question is, “What do you do with the output?” Oftentimes, we will capture the output and store it in a variable. Here’s some sample code:

function double(num) {
  const result = num * 2; // store the result of num * 2 in the variable result
  return result; // return the value stored in result
}

const doubledNumber = double(3); // store 6 in the variable doubledNumber
console.log(doubleNumber); // writes 6 to console log

This can be shortened down as follows:

function double(num) {
  return num * 2; // return the result of num * 2
}

console.log(double(3)); // writes 6 to console log

To answer the question why you must pass the parameter in again, let me go further with the analogy of the box. When you put something in the box, it transforms it into something else, your output. What you put in the box is no longer there. It was changed into the output.

Pretend that you have a box that changes one kind of fruit into another. Let’s say you put in a banana, and it spits out an orange. Where is the banana? It’s gone. It was changed into an orange. If you catch the orange, you can use it however you like. If you don’t catch it, it just rolls away, and gets lost. :slightly_smiling_face:

1 Like

@wmoore98 Thanks for your thorough response, it’s very helpful!

1 Like