javascript - var NAME = function NAME (){ }; - Function Name used twice -


in javascript, 1 standard way declare function follows:

var add = function(a,b){    return a+b; }; 

however, when repeat function name on right side of syntax, no errors either.

var add = function add(a,b){   return a+b; }; 

what's going on in second case?

there 2 uses of function keyword in javascript: function declarations , function expressions. function declarations don't allow left of keyword, e.g.

function add(a,b){     return a+b; } 

and always require name, e.g. add. meanwhile, examples invoke other type, function expressions, don't require name (but can named!) , always require left, e.g. your

var add = function(a,b){     return a+b; }; 

or single parenthesis:

(function(a,b){     return a+b; })(1,2); // 3 

so we've got vocabulary down, you've got in second example, reprinted—

var add = function add(a,b){     return a+b; }; 

—is function expression (namely, variable assignment add) function happens named.

now, what's purpose of named function expression?

it's expressly accessing function within itself! according mdn's documentation,

if want refer current function inside function body, need create named function expression. this name local function body (scope).

let's rename adds can talk things less confusingly:

var abc = function xyz(a,b){     return a+b; }; 

in above, abc accessible in outer scope, while xyz not be. meanwhile, vice versa: abc not accessible in inner scope, while xyz will be.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -