Search code examples
javascriptvariablesscopevariable-declarationfunction-parameter

In JavaScript: Is a function parameter variable (at the moment of function declaration) equivalent to declaring a variable?


I am currently studying variables and scope in JavaScript (from Kyle Simpson's YDKJS series), and I think I understand how the compiler "allocates memory for a variable a" in the appropriate scope if it encounters an explicit variable declaration such as var a;. My question is: In the case of function declarations, such as function foo(a) {...}; if a hasn't been declared as a variable elsewhere yet, does the compiler "declare" that variable so it exists in the function's scope? Or is it that a "doesn't exist" until the function is called foo(3); and a assigned a value?

Sorry if this isn't relevant or if it is too basic. I am trying to fully grasp the idea of scope and variable declaration, and that came as something that I couldn't answer or find by doing some research.

Thanks in advance!


Solution

  • Yes, the named function parameter is a declaration just like var a is. When the scope (in this case the function scope) is entered, the memory is reserved for all declared variables. Then it is initialised with the passed argument (3) - or with undefined if no argument was passed.