Is an anonymous function as a parameter a function declaration or a function expression?

58 views Asked by At

Assuming a function declaration is a statement where the function keyword is the first word of the statement, e.g.:

function() { console.log("foo") };

Assuming that a function expression is e.g. following:

for a named function

var func = function doSomething() { console.log("foo") };

for an anonymous function

var func = function() { console.log("foo") };

What is the case for the anonymous function, which is passed in as parameter in the following example:

for (let i = 0; i < 5; i++) {
    setTimeout(function() { console.log(i); }, 200); 
};

Is that a function declaration or is it a function expression since it is getting assigned to a parameter-variable of the setTimeout-method of WindowOrWorkerGlobalScope

1

There are 1 answers

0
yunzen On

Clearly a function expression

From MDN

Function expression

The function keyword can be used to define a function inside an expression.


Syntax

let myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
   statements
};

A function expression is very similar to and has almost the same syntax as a function declaration (see function statement for details). The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information.



Function declaration

Syntax

function name([param[, param,[..., param]]]) {
   [statements]
}