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.
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.
Share Improve this question asked Jan 25, 2017 at 19:53 SamSam 1892 silver badges10 bronze badges 3- What do you see? What did you expect to see? – Bergi Commented Jan 25, 2017 at 19:58
- Possible duplicate of stackoverflow./questions/30748819/… – DJ. Commented Jan 25, 2017 at 20:01
- Possible duplicate of JavaScript function parameter and scope – DJ. Commented Jan 25, 2017 at 20:01
2 Answers
Reset to default 4Referencing 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/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.