Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Help me understand how this function is interpreted

So, I'm following the videos and have written this out:

function exec(func, arg) {
  func(arg);
}

exec((something) => {
  console.log(something);
}, 'greetings');

I understand this section below is required for the rest of the function to execute. In the console it say that it's needed to define the variable exec.

function exec(func, arg) {
  func(arg);
}

So, is there a difference between how the variable is declared here

var f = function exec (something) {
console.log(something)
};

and how exec is the name of the function here?

function exec (something) {
console.log(something)
};

I'm just not understanding how the first half is required, since a variable actually isn't defined, only a function is defined, and then in the second half it's passed arguments to perform.

1 Answer

Steven Parker
Steven Parker
215,940 Points

These are two different ways of creating a function. Your first example is a function expression:

var f = function exec(something) {
  console.log(something)
};

This creates "f" as the function. The function has a name of "exec" (f.name) but otherwise the word "exec" is not defined elsewhere in the program. "f" can be called after this operation is performed.

Your second example is a function declaration:

function exec(something) {
  console.log(something)
};

In this case, the function "exec" is created. And a declaration is hoisted which means "exec" can be called from anywhere in the program, even before the declaration.

For more details, see the MDN pages on function expression and function declaration.