What is the scope of function parameter in Javascript
var greetFunc = function(name){
var something;
}
console.log("Hello" +name);
console.log(something);
I understand the scope of something is just inside the function, it will not exist outside that. But what about name. Why the value is blank for name variable.
The parameter name is similar to declaring a variable name at the top of the function. So the scope of a parameter is the function it is a part of.
Local variables have their scope to the function only in which they are declared, while global variables have scope to the program and they can be accessed by any function in the program.
Function parameters are the names listed in the function definition. Function arguments are the real values passed to (and received by) the function.
Function scoped variables: A function scoped variable means that the variable defined within a function will not accessible from outside the function. Block scoped variables: A block scoped variable means that the variable defined within a block will not be accessible from outside the block.
Referencing name
outside the function doesn't throw an error like you would expect because it is actually a global variable in every page, part of the global window
object. Typing name
is the same as window.name
.
The something
variable causes an error because it hasn't been defined yet. However, the name variable doesn't cause any problems because it is blank by default, at least in Chrome. You are correct that variables created in a function don't exist outside it.
See https://developer.mozilla.org/en-US/docs/Web/API/Window/name for details.
The parameter name
is similar to declaring a variable name
at the top of the function.
So the scope of a parameter is the function it is a part of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With